Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Add example of AJAX form submission.

Credit goes to @SystemParadox. Originally developed at #DjangoCon Europe
but wasn't tested enough to merge in.

For history, please see https://github.com/pydanny/django/pull/4
  • Loading branch information...
commit b16f8b5fbe4d912daa48b0209dea871b854d8376 1 parent bfa9fc6
Marc Tamlyn authored July 09, 2012
40  docs/topics/class-based-views/generic-editing.txt
@@ -203,3 +203,43 @@ Note that you'll need to :ref:`decorate this
203 203
 view<decorating-class-based-views>` using
204 204
 :func:`~django.contrib.auth.decorators.login_required`, or
205 205
 alternatively handle unauthorised users in the :meth:`form_valid()`.
  206
+
  207
+AJAX example
  208
+------------
  209
+
  210
+Here is a simple example showing how you might go about implementing a form that
  211
+works for AJAX requests as well as 'normal' form POSTs::
  212
+
  213
+    import json
  214
+
  215
+    from django.http import HttpResponse
  216
+    from django.views.generic.edit import CreateView
  217
+    from django.views.generic.detail import SingleObjectTemplateResponseMixin
  218
+
  219
+    class AjaxableResponseMixin(object):
  220
+        """
  221
+        Mixin to add AJAX support to a form.
  222
+        Must be used with an object-based FormView (e.g. CreateView)
  223
+        """
  224
+        def render_to_json_response(self, context, **response_kwargs):
  225
+            data = json.dumps(context)
  226
+            response_kwargs['content_type'] = 'application/json'
  227
+            return HttpResponse(data, **response_kwargs)
  228
+
  229
+        def form_invalid(self, form):
  230
+            if self.request.is_ajax():
  231
+                return self.render_to_json_response(form.errors, status=400)
  232
+            else:
  233
+                return super(AjaxableResponseMixin, self).form_invalid(form)
  234
+
  235
+        def form_valid(self, form):
  236
+            if self.request.is_ajax():
  237
+                data = {
  238
+                    'pk': form.instance.pk,
  239
+                }
  240
+                return self.render_to_json_response(data)
  241
+            else:
  242
+                return super(AjaxableResponseMixin, self).form_valid(form)
  243
+
  244
+    class AuthorCreate(AjaxableResponseMixin, CreateView):
  245
+        model = Author

0 notes on commit b16f8b5

Please sign in to comment.
Something went wrong with that request. Please try again.