AJAXForeignKey: views.py

File views.py, 2.1 KB (added by Michael Axiak <axiak@…>, 18 years ago)

Ajax View

Line 
1from django.contrib.auth.decorators import login_required, user_passes_test
2from django.core import serializers
3from django.http import HttpResponse
4from django.utils import simplejson
5from django.db.models.query import QuerySet
6from django.db import models
7
8user_is_staff = user_passes_test(lambda u: u.is_staff and u.is_authenticated())
9
10@user_is_staff
11def ajax_autocomplete(request):
12 """
13 This function will recieve a bunch fo GET requests for the
14 AjaxForeignKey, and return the data for the autocompletion.
15 """
16 try:
17 limit = int(request.GET.get('limit',10))
18 model_module = request.GET['model_module']
19 model_name = request.GET['model_name']
20 ajax_func = request.GET.get('ajax_func', 'ajax_autocomplete')
21 data = request.GET['ajax_data']
22 except KeyError, ValueError:
23 # bad request
24 response = HttpResponse('Malformed Input')
25 response.status_code = 400
26 return response
27
28 # import the model
29 Model = getattr(__import__(model_module,(),(),['']),model_name)
30
31 if not issubclass(Model, models.Model):
32 raise ValueError, "Required a model"
33
34 if hasattr(Model.objects, ajax_func):
35 query_set = getattr(Model.objects, ajax_func)(data)
36 else:
37 query_set = getattr(Model, ajax_func)(data)
38
39 if type(query_set) == QuerySet:
40 output = list(query_set[:limit])
41 output2 = []
42
43 for item in output:
44 if hasattr(item, 'ajax_str'):
45 ajax_str = item.ajax_str()
46 else:
47 ajax_str = str(item)
48
49 output2.append({'id': item['id'], 'ajax_str': ajax_str+' (%s)' % item['id']})
50 else:
51 output = list(query_set[:limit])
52 output2 = []
53 for item in output:
54 output2.append({'id': item['id'], 'ajax_str': item['ajax_str']+' (%s)' % item['id']})
55
56 content = simplejson.dumps({'result':output2})
57
58 return HttpResponse(content,
59 mimetype = 'javascript/javascript')
Back to Top