Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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
Tim Graham authored
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 89e809c

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