Reputation: 1347
I tried to use SuccessMessageMixin with CreateView but got an error.
I used it with UpdateView and it worked.
It'd be nice to get a hint about what to do next. Thanks.
Repo: https://github.com/jeremy886/DjangoBasics/blob/DjangoForms/courses/views.py
Error:
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
Code:
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
Upvotes: 3
Views: 1379
Reputation: 47374
The problem is in form_valid
function: return super().form_valid(quiz_form)
. It should be return super().form_valid(form)
instead.
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)
Upvotes: 3