我正在尝试创建一个测验,其中包含用户在表单中输入的一些问题(也带有标签,但这不是重点)。我尝试了以下但我不认为这是正确的方法。我认为必须有另一种方式,而不是手动调用Quiz.objects.create()与我从表单中获得的数据。即使创建了Quiz对象,我也会收到以下错误:
'NoneType' object has no attribute '__dict__'
models.py
class Quiz(models.Model):
name = models.CharField(max_length=100)
number_of_questions = models.IntegerField(default=5)
time_limit = models.IntegerField(default=300)
questions = models.ManyToManyField(Question)
forms.py
class QuizForm(forms.ModelForm):
class Meta:
model = Quiz
exclude = ['questions']
def save(self):
data = self.cleaned_data
questions = get_questions_with_tag('example_tag')
questions = questions[:data['number_of_questions']]
quiz = Quiz.objects.create(name=data['name'],
time_limit=data['time_limit'],
number_of_questions=data['number_of_questions'])
for q in questions:
quiz.questions.add(q)
quiz.save()
views.py
class AddQuizView(CreateView):
template_name = 'quiz/cpanel/add_quiz.html'
form_class = QuizForm
success_url = reverse_lazy('list_quizzes')
您能否建议一种更好的方法,只需将问题列表添加到表单请求中?
答案 0 :(得分:0)
经过几次尝试后,我想出了这个:
def save(self):
data = self.cleaned_data
questions = get_questions_with_tag('example_tag')
questions = questions[:data['number_of_questions']]
self.instance.save()
self.instance.questions = questions
quiz.save()
它修复了我的错误,并且我不再手动创建Quiz类型的对象。