Ticket #10402: jquery-autocomplete.txt

File jquery-autocomplete.txt, 2.3 KB (added by DirkDatzert, 16 years ago)

jquery autocomplete views.py/urls.py

Line 
1
2-- views.py ------------
3
4from django.http import HttpResponse, HttpResponseBadRequest
5from django.views.decorators.cache import cache_page
6from django.db.models import Q
7
8# from http://www.djangosnippets.org/snippets/233/
9# generalized for variable queryset and fieldname
10
11def autocomplete(request, queryset, searchfields=[], resultfields=[]):
12 if resultfields:
13 fields = resultfields
14 else:
15 fields = []
16 for searchfield in searchfields:
17 if '__' in searchfield:
18 fields.append(searchfield[:searchfield.index('__')])
19 else:
20 fields.append(searchfield)
21
22 def iter_results(results):
23 if results:
24 for r in results:
25 result = ''
26 for field in fields:
27 value = getattr(r, field)
28 if result:
29 result += '|%s' % value
30 else:
31 result = '%s' % value
32 yield '%s\n' % result
33
34 if not request.GET.get('q'):
35 return HttpResponse(mimetype='text/plain')
36
37 q = request.GET.get('q')
38 limit = request.GET.get('limit', 15)
39
40 try:
41 limit = int(limit)
42 except ValueError:
43 return HttpResponseBadRequest()
44
45 qs = None
46
47 for searchfield in searchfields:
48 kwargs = {}
49 if '__' in searchfield:
50 kwargs[searchfield] = q
51 else:
52 kwargs['%s__istartswith' % searchfield] = q
53 if qs:
54 qs = qs | Q(**kwargs)
55 else:
56 qs = Q(**kwargs)
57
58 object_list = queryset.filter(qs)[:limit]
59 return HttpResponse(iter_results(object_list), mimetype='text/plain')
60
61autocomplete = cache_page(autocomplete, 60 * 60)
62
63
64
65
66
67-- urls.py ---------
68
69# -*- coding: utf-8 -*-
70
71from django.conf.urls.defaults import *
72from models import *
73
74besuch = {
75 'queryset': Besuch.objects.filter(besuchsende__isnull=True).order_by('besuchsbeginn'),
76 'searchfields': ['besucher__name__icontains', 'besucher__firma__name__icontains', 'besuchsempfaenger__name__icontains', 'besuchsziel__ort__icontains'],
77 'resultfields': ['id', 'besucher', 'besuchsempfaenger', 'besuchsziel', 'besuchsbeginn']
78}
79
80urlpatterns += patterns('views',
81 (r'^besuch/search/$', 'autocomplete', besuch ),
82)
83
Back to Top