Home > other >  Problems with global variable Django
Problems with global variable Django

Time:11-25

I write a quiz web site. And i need to save answers from users. Some of them have similar username. This is my start function

global new_user_answer
user_group = request.user.groups.values_list()
university = user_group[0][1]
num = Answers.objects.all().count()
new_user_answer = num   1
new_line = Answers(id=new_user_answer, id_user=user)
new_line.save()
return redirect(f'/1')

Here I create new line in my DB. Second function save user answers.

    data = Answers.objects.get(id=new_user_answer)
    setattr(data, question, answers)
    data.save()
    if int(id_questions) < 47:
        return redirect(f'/{int(id_questions)  1 }')
    else:
        return render(request, 'index.html')

Sometime I have a error 500

name new_user_answer is no define

How I can solve this problem?

CodePudding user response:

Probably it has no sense to use a global variable on that way. You could define a session variable instead (a cookie).

Edit the MIDDLEWARE setting and make sure it contains django.contrib.sessions.middleware.SessionMiddleware.

#start function

user_group = request.user.groups.values_list()
university = user_group[0][1]
num = Answers.objects.all().count()
request.session['new_user_answer'] = num   1
new_line = Answers(id=request.session['new_user_answer'], id_user=user)
new_line.save()
return redirect(f'/1')

#Second function

if 'new_user_answer' in request.session:
    data = Answers.objects.get(id=request.session['new_user_answer'])
    setattr(data, question, answers)
    data.save()
if int(id_questions) < 47:
    return redirect(f'/{int(id_questions)  1 }')
else:
    return render(request, 'index.html')

More info: https://docs.djangoproject.com/en/dev/topics/http/sessions/#session-object-guidelines

  • Related