重写Django Forms的__init__方法-传递request.POST表单时没有数据

时间:2020-04-10 19:15:11

标签: django django-forms

我需要从“问题”数据库(数据库中的实体)生成随机测验。 我已经覆盖了表单的 init 方法

import django.forms as forms
import random
from .models import Question

class ExaminationForm(forms.Form):
    # matricola = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(ExaminationForm, self).__init__(*args, **kwargs)
        if not self.is_bound:

            questions = list(Question.objects.all())
            random_questions = random.sample(questions, k=3)

            for i in range(len(random_questions)):
                field_name = random_questions[i].question_id
                answers = [(random_questions[i].answer_A,random_questions[i].answer_A), (random_questions[i].answer_B,random_questions[i].answer_B), (random_questions[i].answer_C,random_questions[i].answer_C), (random_questions[i].answer_D, random_questions[i].answer_D)]
                random.shuffle(answers)
                self.fields[field_name] = forms.ChoiceField(label=random_questions[i].title, choices=answers, widget=forms.RadioSelect)
        else:
            print('Forms should have data')

以上代码有效,我可以生成带有随机问题的表格

但是当我向服务器发送POST请求时,表单始终没有数据

这是我认为的代码:

if request.method == 'GET':
            form = ExaminationForm()
            context = {
            "has_done":False,
            "form":form
            }
            return render(request, 'examination.html', context)
        elif request.method == 'POST':
            form = ExaminationForm(request.POST)

### HERE THE FORM IS BLANK AND WITHOUT DATA



            if form.is_valid():
                print('Form is valid')
                print(form.fields.values())

                for field in list(form.cleaned_data):
                    print(field)

                return HttpResponseRedirect('/')
            else:
                print('An error occurred')
                print(form.errors)
                return HttpResponseRedirect('/')

0 个答案:

没有答案