首页 > 解决方案 > 无法从 django 中的会话字典的键中提取值

问题描述

我有一个会话变量,用于从用户输入表单保存在我的 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。

标签: djangodjango-sessions

解决方案


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

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)

推荐阅读