1
0
mirror of https://github.com/django/django.git synced 2024-12-22 17:16:24 +00:00

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

Added example of AJAX form submission for CBVs.
This commit is contained in:
Tim Graham 2012-09-17 16:02:07 -07:00
commit 89e809c400

View File

@ -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