1 from django import forms
2 from django.conf import settings
3 from django.contrib.admin.widgets import url_params_from_lookup_dict
4 from django.utils import simplejson as json
5 from django.utils.html import escape
6 from django.utils.safestring import mark_safe
7 from django.utils.text import truncate_words
8 from django.utils.translation import ugettext as _
11 class ModelLookupWidget(forms.TextInput):
14 def __init__(self, content_type, attrs=None, limit_choices_to=None):
15 self.content_type = content_type
16 self.limit_choices_to = limit_choices_to
17 super(ModelLookupWidget, self).__init__(attrs)
19 def render(self, name, value, attrs=None):
20 related_url = '../../../%s/%s/' % (self.content_type.app_label, self.content_type.model)
21 params = url_params_from_lookup_dict(self.limit_choices_to)
23 url = u'?' + u'&'.join([u'%s=%s' % (k, v) for k, v in params.items()])
28 if "class" not in attrs:
29 attrs['class'] = 'vForeignKeyRawIdAdminField'
30 output = [super(ModelLookupWidget, self).render(name, value, attrs)]
31 output.append('<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);">' % (related_url, url, name))
32 output.append('<img src="%simg/admin/selector-search.gif" width="16" height="16" alt="%s" />' % (settings.ADMIN_MEDIA_PREFIX, _('Lookup')))
35 value_class = self.content_type.model_class()
37 value_object = value_class.objects.get(pk=value)
38 output.append(' <strong>%s</strong>' % escape(truncate_words(value_object, 14)))
39 except value_class.DoesNotExist:
41 return mark_safe(u''.join(output))
44 class EmbedWidget(forms.Textarea):
45 """A form widget with the HTML class embedding and an embedded list of content-types."""
46 def __init__(self, attrs=None):
47 from philo.models import value_content_type_limiter
49 content_types = value_content_type_limiter.classes
52 for content_type in content_types:
53 data.append({'app_label': content_type._meta.app_label, 'object_name': content_type._meta.object_name.lower(), 'verbose_name': unicode(content_type._meta.verbose_name)})
55 json_ = json.dumps(data)
57 default_attrs = {'class': 'embedding vLargeTextField', 'data-content-types': json_ }
60 default_attrs.update(attrs)
62 super(EmbedWidget, self).__init__(default_attrs)
66 'all': ('philo/css/EmbedWidget.css',),
68 js = ('philo/js/EmbedWidget.js',)