Search code examples
djangodjango-sessions

Cannot pull the value from the key of a session dictionary in django


I have a session variable for the name of a company saved in my django view from a user input form. When I try and use this in a later view, no matter what I try it pulls the {key: value} pair rather than just the value

Views:

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>

Ive also tried company_name=request.session['company_name'], but both then render as {'company_name': 'test_company'} rather than test_company.


Solution

  • FYI If anyone has a similar issue I've circumvented using

    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)