Мне нужно создать случайную викторину из базы данных вопросов (сущность в БД). Я переопределил 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('/')