How can i make shuffle in django Forms?

huangapple go评论61阅读模式
英文:

How can i make shuffle in django Forms?

问题

我有一个类似于问答游戏的项目,但我需要在问题中对答案进行随机排序。

这是我的代码:

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)

这是我的Django表单。我尝试了这样的方式,但它不起作用:

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
英文:

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

 &lt;form method=&quot;post&quot;&gt;
    {% csrf_token %}
    &lt;h3&gt;{{ current_question.text }}&lt;/h3&gt;
    {{ form.selected_answer }}
     &lt;button type=&quot;submit&quot;&gt;Next&lt;/button&gt;
  &lt;/form&gt;

views.py

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

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

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[&#39;selected_answer&#39;].queryset = answers

答案1

得分: 1

如果答案的数量很少,这里可能是这种情况,你可以使用.order_by('?')来处理。

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<b>.order_by('?')</b>
英文:

If the number of answers is small, which is likely the case here, you can work with .order_by(&#39;?&#39;)&nbsp;<sup>[Django-doc]</sup>:

<pre><code>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[
            &#39;selected_answer&#39;
        ].queryset = question.answer_set&lt;b&gt;.order_by(&#39;?&#39;)&lt;/b&gt;&lt;/code&gt;&lt;/pre&gt;

huangapple
  • 本文由 发表于 2023年8月8日 20:06:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76859397.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定