1 from django import forms
2 from django.conf import settings
3 from django.contrib.admin.widgets import FilteredSelectMultiple
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):
14 self.content_type = content_type
15 super(ModelLookupWidget, self).__init__(attrs)
17 def render(self, name, value, attrs=None):
18 related_url = '../../../%s/%s/' % (self.content_type.app_label, self.content_type.model)
21 if not attrs.has_key('class'):
22 attrs['class'] = 'vForeignKeyRawIdAdminField'
23 output = super(ModelLookupWidget, self).render(name, value, attrs)
24 output += '<a href="%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);">' % (related_url, name)
25 output += '<img src="%simg/admin/selector-search.gif" width="16" height="16" alt="%s" />' % (settings.ADMIN_MEDIA_PREFIX, _('Lookup'))
28 value_class = self.content_type.model_class()
30 value_object = value_class.objects.get(pk=value)
31 output += ' <strong>%s</strong>' % escape(truncate_words(value_object, 14))
32 except value_class.DoesNotExist:
34 return mark_safe(output)
37 class TagFilteredSelectMultiple(FilteredSelectMultiple):
39 A SelectMultiple with a JavaScript filter interface.
41 Note that the resulting JavaScript assumes that the jsi18n
42 catalog has been loaded in the page
45 js = (settings.ADMIN_MEDIA_PREFIX + "js/core.js",
46 settings.ADMIN_MEDIA_PREFIX + "js/SelectBox.js",
47 settings.ADMIN_MEDIA_PREFIX + "js/SelectFilter2.js")
49 if 'staticmedia' in settings.INSTALLED_APPS:
51 js += (staticmedia.url('admin/js/TagCreation.js'),)
53 js += (settings.ADMIN_MEDIA_PREFIX + "js/TagCreation.js",)
55 def render(self, name, value, attrs=None, choices=()):
56 if attrs is None: attrs = {}
57 attrs['class'] = 'selectfilter'
58 if self.is_stacked: attrs['class'] += 'stacked'
59 output = [super(FilteredSelectMultiple, self).render(name, value, attrs, choices)]
60 output.append(u'<script type="text/javascript">addEvent(window, "load", function(e) {')
61 # TODO: "id_" is hard-coded here. This should instead use the correct
62 # API to determine the ID dynamically.
63 output.append(u'SelectFilter.init("id_%s", "%s", %s, "%s"); tagCreation.init("id_%s"); });</script>\n' % \
64 (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), settings.ADMIN_MEDIA_PREFIX, name))
65 return mark_safe(u''.join(output))