Some ajax heavy apps require a lot of views that are merely a wrapper around the form. This generic view can be used for them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | # imports # {{{
from django.utils import simplejson
from django.http import HttpResponse, Http404
from django.utils.functional import Promise
from django.utils.translation import force_unicode
from django.utils.simplejson import JSONEncoder
from django.conf import settings
# }}}
# JSONResponse # {{{
class LazyEncoder(simplejson.JSONEncoder):
def default(self, o):
if isinstance(o, Promise):
return force_unicode(o)
else:
return super(LazyEncoder, self).default(o)
class JSONResponse(HttpResponse):
def __init__(self, data):
HttpResponse.__init__(
self, content=simplejson.dumps(data, cls=LazyEncoder),
#mimetype="text/html",
)
# }}}
# ajax_form_handler # {{{
def ajax_form_handler(
request, form_cls, require_login=True, allow_get=settings.DEBUG
):
if require_login and not request.user.is_authenticated():
raise Http404("login required")
if not allow_get and request.method != "POST":
raise Http404("only post allowed")
if isinstance(form_cls, basestring):
# can take form_cls of the form: "project.app.forms.FormName"
from django.core.urlresolvers import get_mod_func
mod_name, form_name = get_mod_func(form_cls)
form_cls = getattr(__import__(mod_name, {}, {}, ['']), form_name)
form = form_cls(request, request.REQUEST)
if form.is_valid():
return JSONResponse({ 'success': True, 'response': form.save() })
return JSONResponse({ 'success': False, 'errors': form.errors })
# }}}
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Hm. Instead of passing in a boolean 'require_login' I modified snippet to see if require_login was a callable. This lets me pass such things as a lambda that requires a certain permission instead of just requiring a login (and a slight change in the 404 text to 'permission denied')
#
Please login first before commenting.