Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #195 from pydanny/ajax-docs-example

Added example of AJAX form submission for CBVs.
  • Loading branch information...
commit 89e809c4000ba14145e60bf8ea623c1b3e925fd3 2 parents 23d0136 + b16f8b5
@timgraham timgraham authored
Showing with 40 additions and 0 deletions.
  1. +40 −0 docs/topics/class-based-views/generic-editing.txt
View
40 docs/topics/class-based-views/generic-editing.txt
@@ -203,3 +203,43 @@ Note that you'll need to :ref:`decorate this
view<decorating-class-based-views>` using
:func:`~django.contrib.auth.decorators.login_required`, or
alternatively handle unauthorised users in the :meth:`form_valid()`.
+
+AJAX example
+------------
+
+Here is a simple example showing how you might go about implementing a form that
+works for AJAX requests as well as 'normal' form POSTs::
+
+ import json
+
+ from django.http import HttpResponse
+ from django.views.generic.edit import CreateView
+ from django.views.generic.detail import SingleObjectTemplateResponseMixin
+
+ class AjaxableResponseMixin(object):
+ """
+ Mixin to add AJAX support to a form.
+ Must be used with an object-based FormView (e.g. CreateView)
+ """
+ def render_to_json_response(self, context, **response_kwargs):
+ data = json.dumps(context)
+ response_kwargs['content_type'] = 'application/json'
+ return HttpResponse(data, **response_kwargs)
+
+ def form_invalid(self, form):
+ if self.request.is_ajax():
+ return self.render_to_json_response(form.errors, status=400)
+ else:
+ return super(AjaxableResponseMixin, self).form_invalid(form)
+
+ def form_valid(self, form):
+ if self.request.is_ajax():
+ data = {
+ 'pk': form.instance.pk,
+ }
+ return self.render_to_json_response(data)
+ else:
+ return super(AjaxableResponseMixin, self).form_valid(form)
+
+ class AuthorCreate(AjaxableResponseMixin, CreateView):
+ model = Author
Please sign in to comment.
Something went wrong with that request. Please try again.