Skip to content

Commit

Permalink
Merge pull request #195 from pydanny/ajax-docs-example
Browse files Browse the repository at this point in the history
Added example of AJAX form submission for CBVs.
  • Loading branch information
timgraham committed Sep 17, 2012
2 parents 23d0136 + b16f8b5 commit 89e809c
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions docs/topics/class-based-views/generic-editing.txt
Expand Up @@ -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

0 comments on commit 89e809c

Please sign in to comment.