5638
[auf_rh_dae.git] / project / monkey.py
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
8 # 'code'
9 #
10 ###########################################################################
11
12 from django.conf import settings
13 from django.core.urlresolvers import reverse
14 from django.http import HttpResponse
15 from django.forms.util import flatatt
16 from django.utils.safestring import mark_safe
17 from django.template.loader import render_to_string
18
19 import ajax_select.views
20 from ajax_select import get_lookup
21 from ajax_select.fields import AutoCompleteSelectWidget
22
23
24 def fk_ajax_lookup(request, channel):
25 """
26 this view supplies results for both foreign keys and many to many fields
27 """
28
29 # it should come in as GET unless global $.ajaxSetup({type:"POST"}) has
30 # been set in which case we'll support POST
31 if request.method == "GET":
32 # we could also insist on an ajax request
33 if 'q' not in request.GET:
34 return HttpResponse('')
35 query = request.GET['q']
36 else:
37 if 'q' not in request.POST:
38 return HttpResponse('') # suspicious
39 query = request.POST['q']
40
41 lookup_channel = get_lookup(channel)
42
43 if query:
44 instances = lookup_channel.get_query(query, request)
45 else:
46 instances = []
47
48 results = []
49 for item in instances:
50 itemf = lookup_channel.format_item(item)
51 itemf = itemf.replace("\n", "").replace("|", "¦")
52 resultf = lookup_channel.format_result(item)
53 resultf = resultf.replace("\n", "").replace("|", "¦")
54 fk = getattr(lookup_channel, 'fk_key', None)
55 if fk is not None:
56 id = getattr(item, fk)
57 else:
58 id = item.pk
59 results.append("|".join((unicode(id), itemf, resultf)))
60 return HttpResponse("\n".join(results))
61
62
63 def value_from_datadict(self, data, files, name):
64
65 got = data.get(name, None)
66 if got:
67 try:
68 return long(got)
69 except:
70 return got
71 else:
72 return None
73
74
75 def patched_render(self, name, value, attrs=None):
76 """
77 prevention contre les choses supprimees
78 """
79 # precheck existence valeur
80 lookup = get_lookup(self.channel)
81 if value:
82 objs = lookup.get_objects([value])
83 if len(objs) == 0:
84 value = ''
85
86 # copie de django_ajax_selects-1.1.4-py2.6.egg/ajax_select/fields.py
87 value = value or ''
88 final_attrs = self.build_attrs(attrs)
89 self.html_id = final_attrs.pop('id', name)
90
91 lookup = get_lookup(self.channel)
92 if value:
93 objs = lookup.get_objects([value])
94 try:
95 obj = objs[0]
96 except IndexError:
97 raise Exception("%s cannot find object:%s" % (lookup, value))
98 current_result = mark_safe(lookup.format_item(obj))
99 else:
100 current_result = ''
101
102 context = {
103 'name': name,
104 'html_id': self.html_id,
105 'lookup_url': reverse(
106 'ajax_lookup', kwargs={'channel': self.channel}
107 ),
108 'current_id': value,
109 'current_result': current_result,
110 'help_text': self.help_text,
111 'extra_attrs': mark_safe(flatatt(final_attrs)),
112 'func_slug': self.html_id.replace("-", ""),
113 'add_link': self.add_link,
114 'admin_media_prefix': settings.ADMIN_MEDIA_PREFIX
115 }
116
117 return mark_safe(render_to_string((
118 'autocompleteselect_%s.html' % self.channel,
119 'autocompleteselect.html'
120 ), context))
121
122
123 def patch_ajax_selects():
124 ajax_select.views.ajax_lookup = fk_ajax_lookup
125 AutoCompleteSelectWidget.render = patched_render
126 AutoCompleteSelectWidget.value_from_datadict = value_from_datadict