Django.fun

Django button click rendered View twice

i am really new with Django and still learning. I will try to explain my problem as well as possible. On a button click in my template i want to work with some values & variables:

<form method='get' action=''>
<input type="submit" value="{{ answer1 }}" name="btn1" />
<input type="submit" value="{{ answer2 }}" name="btn2" />
<input type="submit" value="{{ answer3 }}" name="btn3" />
<input type="submit" value="{{ answer4 }}" name="btn4" />
</form>

my views.py:

class MyView(TemplateView):

def get(self, request, *args, **kwargs):
    obj = MyObject()
    self.create_dict(q_obj)      

    if request.GET.get('btn1'):
       # some code...
return render(request, self.template_name, { ... })

The Problem is now whenever i click the button, the used dictionary variable got replaced with the next one because there is a new rendering.

[12/Jan/2022 21:48:46] "GET /quizapp/home/subject/ HTTP/1.1" 200 5267
{'answer': <Answer: 3>, 'correct': False}
{'answer': <Answer: 5>, 'correct': False}
{'answer': <Answer: 2>, 'correct': True}
{'answer': <Answer: 7>, 'correct': False}
[12/Jan/2022 21:48:47] "GET /quizapp/home/subject/round/ HTTP/1.1" 200 7864
{'answer': <Answer: 4>, 'correct': True}
{'answer': <Answer: 2>, 'correct': False}
{'answer': <Answer: 6>, 'correct': False}
{'answer': <Answer: 1>, 'correct': False}

i want to work with the first set but everything i change relates to the second dictionary. I tried fixing with some redirect commands but nothing works... i am misunderstanding some Django(GET/POST) techniques here? Thanks if someone can help me ;)

Answers: 1

Answered by Ball Hog, Jan. 13, 2022, 2:08 a.m.

Submit button anywhere on the internet means you are done dealing with this form and want to go to the next step. Since all of your quiz choices are submit buttons it is not a surprize to get a new render whenever you click on them.

You are submitting the form whenever you click on any of those buttons. You need to implement a radio button (Choices) to avoid that. And only one submit button at the end of the form. An example is provided here

Each time you submit your form it would render it again. Thus you should only press submit when you want to get a new form and go to the next step.