Skip to content

Instantly share code, notes, and snippets.

@eugena
Last active September 11, 2015 13:38
Show Gist options
  • Save eugena/d682e9ff7681eabb6243 to your computer and use it in GitHub Desktop.
Save eugena/d682e9ff7681eabb6243 to your computer and use it in GitHub Desktop.
Mixin to adding AJAX support to a form view.
from django.http import JsonResponse
from django.conf import settings
from django_remote_forms.forms import RemoteForm
class JsonableFormMixin(object):
"""
Mixin to adding AJAX support to a form view.
Must be used with django model editing views
"""
def get(self, request, *args, **kwargs):
"""
Handles GET requests and instantiates a blank version of the form.
"""
if self.request.is_ajax():
form_dict = RemoteForm(self.get_form()).as_dict()
if settings.CSRF_COOKIE_NAME in request.COOKIES.keys():
form_dict['csrfmiddlewaretoken'] = request.COOKIES[settings.CSRF_COOKIE_NAME]
response = JsonResponse(form_dict, safe=False)
else:
response = super(JsonableFormMixin, self).get(self)
return response
def form_invalid(self, form):
"""
If the form is invalid, re-render the context data with the
data-filled form and errors.
"""
if self.request.is_ajax():
response = JsonResponse(form.errors, status=400)
else:
response = super(JsonableFormMixin, self).form_invalid(form)
return response
def form_valid(self, form):
"""
We make sure to call the parent's form_valid() method because
it might do some processing (in the case of CreateView, it will
call form.save() for example).
"""
if self.request.is_ajax():
data = {
'pk': self.object.pk,
}
response = JsonResponse(data)
else:
response = super(JsonableFormMixin, self).form_valid(form)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment