Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i make shuffle in django Forms?

I have got a project like quiz. But i need to shuffle the answers in questions.
here is my code:
template.html

 <form method="post">
    {% csrf_token %}
    <h3>{{ current_question.text }}</h3>
    {{ form.selected_answer }}
     <button type="submit">Next</button>
  </form>

views.py

        if request.method == 'POST':
            form = QuestionForm(request.POST, question=current_question)
            if form.is_valid():
                user_answer = form.cleaned_data['selected_answer']
                user_test.useranswer_set.update_or_create(question=current_question,
                                                          defaults={'selected_answer': user_answer})
                return redirect('test', test_id=test_id)
        else:
            form = QuestionForm(question=current_question)

There is my django form. I try like this but it doesn’t work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from django import forms
from .models import Answer
import random
from django.db.models.query import QuerySet


class QuestionForm(forms.Form):
    selected_answer = forms.ModelChoiceField(
        queryset=Answer.objects.none(),
        widget=forms.RadioSelect,
        empty_label=None
    )

    def __init__(self, *args, question=None, **kwargs):
        super().__init__(*args, **kwargs)
        if question:
            answers = list(question.answer_set.all())
            random.shuffle(answers)
            self.fields['selected_answer'].queryset = answers

>Solution :

If the number of answers is small, which is likely the case here, you can work with .order_by('?') [Django-doc]:

class QuestionForm(forms.Form):
    selected_answer = forms.ModelChoiceField(
        queryset=Answer.objects.none(), widget=forms.RadioSelect, empty_label=None
    )

    def __init__(self, *args, question=None, **kwargs):
        super().__init__(*args, **kwargs)
        if question:
            self.fields[
                'selected_answer'
            ].queryset = question.answer_set.order_by('?')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading