Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect
- from django.utils import simplejson as json
- from django.conf import settings
- class AjaxError(Exception):
- def __init__(self, message, status=200):
- super(AjaxError, self).__init__(message)
- self.status = status
- def ajax_view(function_view):
- """
- Always return a valid ajax response with status code = 200.
- The decorated function just have to return a dictionary that will be
- converted to JSON and that JSON will be included in the HttpResponse.
- When the decorated function fails, the returned JSON will include just an
- 'error' attr with the description of the error. This descriptin
- will be the exception message if the raised exception is an AjaxError
- instance or "Internal error" otherwise.
- """
- def _wrapped_view(request, *args, **kwargs):
- if not request.is_ajax():
- return HttpResponseBadRequest()
- status = 200
- try:
- response = function_view(request, *args, **kwargs)
- if type(response) == HttpResponseRedirect:
- raise AjaxError("Permission denied")
- error = None
- except AjaxError, e:
- response = {}
- error = unicode(e)
- status = e.status
- except Exception, e:
- response = {}
- error = "Internal Error"
- if settings.DEBUG:
- raise
- response.update({'error': error})
- return HttpResponse(
- json.dumps(response if status == 200 else response['error']),
- content_type='application/json; charset=utf8',
- status=status,
- )
- return _wrapped_view
- def get_parameter_or_ajax_error(parameters, key):
- """
- Intended to avoid code repetition when checking if the ajax request includes
- the required parameters.
- The first argument should be request.POST or request.GET
- """
- if not key:
- raise AjaxError('"%s" is not a valid parameter name' % key)
- value = parameters.get(key, None)
- if value is None:
- raise AjaxError('Invalid input data (%s is null)' % key)
- return value
- def get_boolean_parameter_or_ajax_error(parameters, key):
- """
- Same as get_parameter_or_ajax_error but for boolean values. The idea is to
- avoid some known gotchas related to boolean parameters.
- """
- if not key:
- raise AjaxError('"%s" is not a valid parameter name' % key)
- value = parameters.get(key, None)
- if value is None:
- raise AjaxError('Invalid input data (%s is null)' % key)
- if value == 'False' or value == 'false' or value == '0' or value == 0:
- value = False
- elif value:
- value = True
- else:
- value = False
- return value
- def get_list_parameter_or_ajax_error(parameters, key):
- """
- Same as get_parameter_or_ajax_error but for lists. The idea is to
- avoid some known gotchas related to list parameters.
- """
- if not key:
- raise AjaxError('"%s" is not a valid parameter name' % key)
- value = parameters.getlist(key, None)
- if value is None:
- raise AjaxError('Invalid input data (%s is null)' % key)
- return value
- # Usage:
- # @ajax_view
- # @user_passes_test(lambda u: u.is_staff)
- # def cms_search_companies_ajax(request):
- #
- # country_pk = get_parameter_or_ajax_error(request.GET, 'country_pk')
- # city_pk = get_parameter_or_ajax_error(request.GET, 'city_pk')
- # query = get_parameter_or_ajax_error(request.GET, 'query')
- #
- # params = {}
- # if city_pk:
- # params['city__pk'] = city_pk
- # elif country_pk:
- # params['city__country__pk'] = country_pk
- # if query:
- # params['name__icontains'] = query
- return {
- 'targets': [{
- 'value': company.pk,
- 'text': company.name
- } for company in Company.objects.filter(**params)]
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement