Commit | Line | Data |
---|---|---|
ad1eb1db OL |
1 | # -*- encoding: utf-8 -*- |
2 | ||
3 | ################################################################################ | |
4 | # | |
5 | # PATCH AJAX SELECT FIELD : pour gérer le fait que certaine FK ne sont pas | |
6 | # forcément mappé sur la PK du modèle, dans notre cas ici c'est le modèle | |
7 | # Pays qui dispose d'un pk sur son id mais les fk sont mappé sur le champs 'code' | |
8 | # | |
9 | ################################################################################ | |
10 | from ajax_select import get_lookup | |
11 | from django.contrib.admin import site | |
12 | from django.db import models | |
13 | from django.http import HttpResponse | |
14 | import ajax_select.views | |
15 | ||
16 | def fk_ajax_lookup(request,channel): | |
17 | """ this view supplies results for both foreign keys and many to many fields """ | |
18 | ||
19 | # it should come in as GET unless global $.ajaxSetup({type:"POST"}) has been set | |
20 | # in which case we'll support POST | |
21 | if request.method == "GET": | |
22 | # we could also insist on an ajax request | |
23 | if 'q' not in request.GET: | |
24 | return HttpResponse('') | |
25 | query = request.GET['q'] | |
26 | else: | |
27 | if 'q' not in request.POST: | |
28 | return HttpResponse('') # suspicious | |
29 | query = request.POST['q'] | |
30 | ||
31 | lookup_channel = get_lookup(channel) | |
32 | ||
33 | if query: | |
34 | instances = lookup_channel.get_query(query,request) | |
35 | else: | |
36 | instances = [] | |
37 | ||
38 | results = [] | |
39 | for item in instances: | |
40 | itemf = lookup_channel.format_item(item) | |
41 | itemf = itemf.replace("\n","").replace("|","¦") | |
42 | resultf = lookup_channel.format_result(item) | |
43 | resultf = resultf.replace("\n","").replace("|","¦") | |
44 | fk = getattr(lookup_channel, 'fk_key', None) | |
45 | if fk is not None: | |
46 | id = getattr(item, fk) | |
47 | else: | |
48 | id = item.pk | |
49 | results.append( "|".join((unicode(id),itemf,resultf)) ) | |
50 | return HttpResponse("\n".join(results)) | |
51 | ||
52 | ajax_select.views.ajax_lookup = fk_ajax_lookup | |
53 | ||
54 | from ajax_select.fields import AutoCompleteSelectWidget | |
55 | ||
56 | def value_from_datadict(self, data, files, name): | |
57 | ||
58 | got = data.get(name, None) | |
59 | if got: | |
60 | try: | |
61 | return long(got) | |
62 | except: | |
63 | return got | |
64 | else: | |
65 | return None | |
66 | ||
67 | AutoCompleteSelectWidget.value_from_datadict = value_from_datadict |