我尝试在CreateView中使用SuccessMessageMixin,但收到错误。
我在UpdateView中使用它并且它有效。
很高兴得到关于下一步该做什么的提示。感谢。
回购:https://github.com/jeremy886/DjangoBasics/blob/DjangoForms/courses/views.py
错误:
AttributeError at /courses/2/create_quiz/
'Quiz' object has no attribute 'cleaned_data'
Request Method: POST
Request URL: http://localhost:8000/courses/2/create_quiz/
Django Version: 2.0.5
Exception Type: AttributeError
Exception Value:
'Quiz' object has no attribute 'cleaned_data'
Exception Location: C:\Users\jeremy\.virtualenvs\django\lib\site-packages\django\contrib\messages\views.py in form_valid, line 12
代码:
class QuizCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
model = "course"
pk_url_kwarg = "course_pk"
context_object_name = 'course'
form_class = forms.QuizForm
template_name = "courses/quiz_create.html"
success_message = "%(title)s was created successfully"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
course_pk = self.kwargs.get(self.pk_url_kwarg)
course = get_object_or_404(models.Course, pk=course_pk)
context["course"] = course
return context
def form_valid(self, form):
course_pk = self.kwargs.get(self.pk_url_kwarg)
quiz_form = form.save(commit=False)
quiz_form.course = get_object_or_404(models.Course, pk=course_pk)
# find a way to add "Successfully added!" message
return super().form_valid(quiz_form)
def get_success_url(self):
course_pk = self.kwargs["course_pk"]
return reverse_lazy('courses:detail', kwargs={'pk': course_pk})
# More: how to get the quiz id from the above quiz form
答案 0 :(得分:3)
问题出在form_valid
函数:return super().form_valid(quiz_form)
。它应该是return super().form_valid(form)
。
def form_valid(self, form):
course_pk = self.kwargs.get(self.pk_url_kwarg)
form.instance.course = get_object_or_404(models.Course, pk=course_pk)
return super().form_valid(form)