2 from django
.utils
import simplejson
3 from django
.http
import HttpResponse
, Http404
, HttpResponseServerError
4 from django
.http
import HttpResponseRedirect
5 from django
.utils
.functional
import Promise
6 from django
.utils
.translation
import force_unicode
7 from django
.utils
.simplejson
import JSONEncoder
8 from django
.conf
import settings
9 from django
import forms
13 class LazyEncoder(simplejson
.JSONEncoder
):
15 if isinstance(o
, Promise
):
16 return force_unicode(o
)
18 return super(LazyEncoder
, self
).default(o
)
20 class JSONResponse(HttpResponse
):
21 def __init__(self
, data
):
23 HttpResponse
.__init
__(
24 self
, content
=simplejson
.dumps(data
, cls
=LazyEncoder
),
25 #mimetype="text/html",
29 # ajax_form_handler # {{{
30 def ajax_form_handler(
31 request
, form_cls
, require_login
=True, allow_get
=settings
.DEBUG
33 if require_login
and not request
.user
.is_authenticated():
34 raise Http404("login required")
35 if not allow_get
and request
.method
!= "POST":
36 raise Http404("only post allowed")
37 if isinstance(form_cls
, basestring
):
38 # can take form_cls of the form: "worddb.app.forms.FormName"
39 from django
.core
.urlresolvers
import get_mod_func
40 mod_name
, form_name
= get_mod_func(form_cls
)
41 form_cls
= getattr(__import__(mod_name
, {}, {}, ['']), form_name
)
42 form
= form_cls(request
, request
.REQUEST
)
44 response
= form
.save()
45 if request
.is_ajax() or request
.REQUEST
.get("is_ajax"):
46 return JSONResponse({ 'success': True, 'response': response
})
48 return HttpResponseRedirect(request
.META
.get("HTTP_REFERER", ""))
49 return JSONResponse({ 'success': False, 'errors': form
.errors
})
52 # ajax_validator # {{{
53 def ajax_validator(request
, form_cls
):
54 if isinstance(form_cls
, basestring
):
55 from django
.core
.urlresolvers
import get_mod_func
56 mod_name
, form_name
= get_mod_func(form_cls
)
57 form_cls
= getattr(__import__(mod_name
, {}, {}, ['']), form_name
)
58 form
= form_cls(request
.POST
)
59 if "field" in request
.GET
:
60 errors
= form
.errors
.get(request
.GET
["field"])
61 if errors
: errors
= errors
.as_text()
65 { "errors": errors
, "valid": not errors
}
72 settings
.WORD_FORM_DELIMITER
, form
, settings
.WORD_FORM_DELIMITER
76 # AJAXSimpleExceptionResponse www.djangosnippets.org/snippets/650/ # {{{
77 class AJAXSimpleExceptionResponse
:
78 def process_exception(self
, request
, exception
):
80 (exc_type
, exc_info
, tb
) = sys
.exc_info()
81 response
= "%s\n" % exc_type
.__name
__
82 response
+= "%s\n\n" % exc_info
83 response
+= "TRACEBACK:\n"
84 for tb
in traceback
.format_tb(tb
):
85 response
+= "%s\n" % tb
87 if not settings
.DEBUG
: return
88 if not request
.is_ajax(): return
89 return HttpResponseServerError(response
)
93 def no_new_lines(field
):
95 if "xx" in self
.cleaned_data
.get(field
, ""):
96 raise forms
.ValidationError("New line not allowed")
97 return self
.cleaned_data
.get(field
)