【问题标题】:Cannot pull the value from the key of a session dictionary in django无法从 django 中的会话字典的键中提取值
【发布时间】:2021-01-21 18:17:50
【问题描述】:

我有一个会话变量,用于从用户输入表单保存在我的 django 视图中的公司名称。当我尝试在以后的视图中使用它时,无论我尝试什么,它都会拉出 {key: value} 对而不仅仅是值

观看次数:

def start(request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = QuizTakerForm(request.POST )
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            post = form.save(commit=False)
            post.user = request.user
            post.save()
            request.session['obj_id'] = post.id
            request.session['company_name'] = form.cleaned_data
            # redirect to a new URL:
            return HttpResponseRedirect('industry/')
....

def Gov_q1(request):
    company_name = request.session.get('company_name')
    print(company_name)
    question = Question.objects.get(pk=24)
    context = {'question': question, 'company_name': company_name}
    return render(request, 'ImpactCheck/detail.html', context)

html:

<h1> Hi my name is {{ company_name }} </h1>
<h1>{{ question.text }}</h1>
<form action="." method="post">

{% for answer in question.answer_set.all %}
      <input type="radio" name="answer" id="answer" value="{{ answer.id }}">
      <label for="answer">{{ answer.answer_text }}</label><br>
  {% endfor %}
  <input type="submit" value="Submit">
  </form>

我也尝试过 company_name=request.session['company_name'],但两者都呈现为 {'company_name': 'test_company'} 而不是 test_company。

【问题讨论】:

    标签: django django-sessions


    【解决方案1】:

    仅供参考,如果有人有类似的问题,我已经绕过了

    def Gov_q1(request):
        id=request.session.get('obj_id')
        company_name= QuizTakers.objects.get(pk=id)
        question = Question.objects.get(pk=24)
        context = {'question': question, 'company_name': company_name, 'cn': cn}
        return render(request, 'ImpactCheck/detail.html', context)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-04
      • 2013-06-09
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 2016-06-24
      • 2011-07-18
      相关资源
      最近更新 更多