I'm still a noob at mixins in general so I'm just trying to understand what happens in this code that uses Ajax to submit forms. I've been scouring the docs for a whole day to try to figure out what happens. The code seems to work but I just don't entirely understand why. I still have a lot of question marks on the whole process so if anyone can correct my thinking that would be amazing
The AjaxableResponseMixin extends the form_invalid() and form_valid() methods of the FormView to support Ajax requests
- Why is the Ajax class referring to itself with super()?
- How does the class know to extend FormView's methods?
If the request is not Ajax it returns response
- What does the response object do/have? Does it show a template? Does it have context for the template?
CreatePostView is a child class of the two parent classes that are passed in (AjaxableResponseMixin, FormView)
- Do the order of the classes in the params have an impact in general and more specifically when calling super()?
- When CreatePostView calls form_valid() and form_invalid() is it overwriting the Ajax class? If it isn't, what class methods is it changing?
If the form is valid then a post gets created and super().form_valid() gets called which then redirects to the success url because thats what the FormView.form_valid() does
- Again, why is the super() referring to the FormView?
- Am I better off just doing a HttpResponseRedirect instead of using super().form_valid()
If the form is invalid it redirects to the url with the "create_post" name
- How do I redirect to the create post page and keep the data in the form the user tried to submit?
views.py
class AjaxableResponseMixin(object):
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
return JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
response = super(AjaxableResponseMixin, self).form_valid(form)
if self.request.is_ajax():
data = {
'pk': self.object.pk,
}
return JsonResponse(data)
else:
return response
class CreatePostView(AjaxableResponseMixin, FormView):
form_class = CreatePostForm
template_name = 'forum/create_post.html'
success_url = reverse_lazy('home')
def form_valid(self, form):
user = self.request.user
form.create_post(user_obj=user)
messages.success(self.request, 'Your post was published')
return super().form_valid(form)
def form_invalid(self, form):
messages.error(self.request, 'Your post could not be published. Please try again')
return HttpResponseRedirect(reverse('create_post'))
Thank you so much to anybody who answers.