1 from django import forms
2 from django.conf import settings
3 from django.contrib.admin.widgets import FilteredSelectMultiple, url_params_from_lookup_dict
4 from django.utils.translation import ugettext as _
5 from django.utils.safestring import mark_safe
6 from django.utils.text import truncate_words
7 from django.utils.html import escape
10 class ModelLookupWidget(forms.TextInput):
13 def __init__(self, content_type, attrs=None, limit_choices_to=None):
14 self.content_type = content_type
15 self.limit_choices_to = limit_choices_to
16 super(ModelLookupWidget, self).__init__(attrs)
18 def render(self, name, value, attrs=None):
19 related_url = '../../../%s/%s/' % (self.content_type.app_label, self.content_type.model)
20 params = url_params_from_lookup_dict(self.limit_choices_to)
22 url = u'?' + u'&'.join([u'%s=%s' % (k, v) for k, v in params.items()])
27 if "class" not in attrs:
28 attrs['class'] = 'vForeignKeyRawIdAdminField'
29 output = [super(ModelLookupWidget, self).render(name, value, attrs)]
30 output.append('<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);">' % (related_url, url, name))
31 output.append('<img src="%simg/admin/selector-search.gif" width="16" height="16" alt="%s" />' % (settings.ADMIN_MEDIA_PREFIX, _('Lookup')))
34 value_class = self.content_type.model_class()
36 value_object = value_class.objects.get(pk=value)
37 output.append(' <strong>%s</strong>' % escape(truncate_words(value_object, 14)))
38 except value_class.DoesNotExist:
40 return mark_safe(u''.join(output))
43 class TagFilteredSelectMultiple(FilteredSelectMultiple):
45 A SelectMultiple with a JavaScript filter interface.
47 Note that the resulting JavaScript assumes that the jsi18n
48 catalog has been loaded in the page
51 js = (settings.ADMIN_MEDIA_PREFIX + "js/core.js",
52 settings.ADMIN_MEDIA_PREFIX + "js/SelectBox.js",
53 settings.ADMIN_MEDIA_PREFIX + "js/SelectFilter2.js")
55 if 'staticmedia' in settings.INSTALLED_APPS:
57 js += (staticmedia.url('admin/js/TagCreation.js'),)
59 js += (settings.ADMIN_MEDIA_PREFIX + "js/TagCreation.js",)
61 def render(self, name, value, attrs=None, choices=()):
62 if attrs is None: attrs = {}
63 attrs['class'] = 'selectfilter'
64 if self.is_stacked: attrs['class'] += 'stacked'
65 output = [super(FilteredSelectMultiple, self).render(name, value, attrs, choices)]
66 output.append(u'<script type="text/javascript">addEvent(window, "load", function(e) {')
67 # TODO: "id_" is hard-coded here. This should instead use the correct
68 # API to determine the ID dynamically.
69 output.append(u'SelectFilter.init("id_%s", "%s", %s, "%s"); tagCreation.init("id_%s"); });</script>\n' % \
70 (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), settings.ADMIN_MEDIA_PREFIX, name))
71 return mark_safe(u''.join(output))