[#2534] Fait du champ "ref" dans EtablissementBase un champ one-to-one
[auf_django_references.git] / auf / django / references / forms.py
1 # encoding: utf-8
2
3 from django import forms
4 from django.utils.safestring import mark_safe
5
6 from auf.django.references import models as ref
7
8
9 class EtablissementAutocompleteWidget(forms.TextInput):
10 """
11 Champ texte qui émet les invocations javascript pour gérer
12 l'autocomplétion des établissements.
13 """
14
15 def __init__(self):
16 super(EtablissementAutocompleteWidget, self).__init__(attrs={
17 'autocomplete': 'off'
18 });
19 self.exclude_refs = None
20
21 def render(self, name, value, attrs=None):
22 widget = super(EtablissementAutocompleteWidget, self).render(name, value, attrs=attrs)
23 id = attrs and attrs.get('id')
24 if id:
25 args = ("'%s'" % self.exclude_refs) if self.exclude_refs else ''
26 js = """
27 <script type="text/javascript">
28 $(function() { $('#%s').etablissement_autocomplete(%s); })
29 </script>
30 """ % (id, args)
31 widget += js
32 return mark_safe(widget)
33
34
35 class EtablissementForm(forms.ModelForm):
36 nom = forms.CharField(widget=EtablissementAutocompleteWidget)
37
38 class Meta:
39 model = ref.EtablissementBase
40
41 class Media:
42 css = {
43 'screen': ('references/jquery-ui.css',)
44 }
45 js = (
46 'references/jquery.min.js',
47 'references/jquery-ui.min.js',
48 'references/jquery.etablissement-autocomplete.js',
49 )
50
51 def __init__(self, *args, **kwargs):
52 super(EtablissementForm, self).__init__(*args, **kwargs)
53 model = self._meta.model
54 ref_name = model._meta.get_field('ref').rel.related_name
55 self.fields['nom'].widget.exclude_refs = ref_name