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
This commit is contained in:
Marc Tamlyn 2012-07-09 08:58:24 +01:00
parent bfa9fc69bf
commit b16f8b5fbe
1 changed files with 40 additions and 0 deletions

View File

@ -203,3 +203,43 @@ Note that you'll need to :ref:`decorate this
view<decorating-class-based-views>` using view<decorating-class-based-views>` using
:func:`~django.contrib.auth.decorators.login_required`, or :func:`~django.contrib.auth.decorators.login_required`, or
alternatively handle unauthorised users in the :meth:`form_valid()`. 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