1 from django.conf import settings
2 from django.contrib import admin
3 from django.contrib.contenttypes import generic
4 from django.http import HttpResponse
5 from django.utils import simplejson as json
6 from django.utils.html import escape
7 from mptt.admin import MPTTModelAdmin
9 from philo.models import Tag, Attribute
10 from philo.models.fields.entities import ForeignKeyAttribute, ManyToManyAttribute
11 from philo.admin.forms.attributes import AttributeForm, AttributeInlineFormSet
12 from philo.admin.widgets import TagFilteredSelectMultiple
13 from philo.forms.entities import EntityForm, proxy_fields_for_entity_model
16 COLLAPSE_CLASSES = ('collapse', 'collapse-closed', 'closed',)
19 class AttributeInline(generic.GenericTabularInline):
20 ct_field = 'entity_content_type'
21 ct_fk_field = 'entity_object_id'
25 classes = COLLAPSE_CLASSES
27 formset = AttributeInlineFormSet
28 fields = ['key', 'value_content_type']
29 if 'grappelli' in settings.INSTALLED_APPS:
30 template = 'admin/philo/edit_inline/grappelli_tabular_attribute.html'
32 template = 'admin/philo/edit_inline/tabular_attribute.html'
35 # HACK to bypass model validation for proxy fields
36 class SpoofedHiddenFields(object):
37 def __init__(self, proxy_fields, value):
39 self.spoofed = list(set(value) - set(proxy_fields))
41 def __get__(self, instance, owner):
47 class SpoofedAddedFields(SpoofedHiddenFields):
48 def __init__(self, proxy_fields, value):
50 self.spoofed = list(set(value) | set(proxy_fields))
53 def hide_proxy_fields(cls, attname):
54 val = getattr(cls, attname, [])
55 proxy_fields = getattr(cls, 'proxy_fields')
57 setattr(cls, attname, SpoofedHiddenFields(proxy_fields, val))
59 def add_proxy_fields(cls, attname):
60 val = getattr(cls, attname, [])
61 proxy_fields = getattr(cls, 'proxy_fields')
62 setattr(cls, attname, SpoofedAddedFields(proxy_fields, val))
65 class EntityAdminMetaclass(admin.ModelAdmin.__metaclass__):
66 def __new__(cls, name, bases, attrs):
67 new_class = super(EntityAdminMetaclass, cls).__new__(cls, name, bases, attrs)
68 hide_proxy_fields(new_class, 'raw_id_fields')
69 add_proxy_fields(new_class, 'readonly_fields')
73 class EntityAdmin(admin.ModelAdmin):
74 __metaclass__ = EntityAdminMetaclass
76 inlines = [AttributeInline]
80 def formfield_for_dbfield(self, db_field, **kwargs):
82 Override the default behavior to provide special formfields for EntityEntitys.
83 Essentially clones the ForeignKey/ManyToManyField special behavior for the Attribute versions.
85 if not db_field.choices and isinstance(db_field, (ForeignKeyAttribute, ManyToManyAttribute)):
86 request = kwargs.pop("request", None)
87 # Combine the field kwargs with any options for formfield_overrides.
88 # Make sure the passed in **kwargs override anything in
89 # formfield_overrides because **kwargs is more specific, and should
91 if db_field.__class__ in self.formfield_overrides:
92 kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs)
94 # Get the correct formfield.
95 if isinstance(db_field, ManyToManyAttribute):
96 formfield = self.formfield_for_manytomanyattribute(db_field, request, **kwargs)
97 elif isinstance(db_field, ForeignKeyAttribute):
98 formfield = self.formfield_for_foreignkeyattribute(db_field, request, **kwargs)
100 # For non-raw_id fields, wrap the widget with a wrapper that adds
101 # extra HTML -- the "add other" interface -- to the end of the
102 # rendered output. formfield can be None if it came from a
103 # OneToOneField with parent_link=True or a M2M intermediary.
104 # TODO: Implement this.
105 #if formfield and db_field.name not in self.raw_id_fields:
106 # formfield.widget = admin.widgets.RelatedFieldWidgetWrapper(formfield.widget, db_field, self.admin_site)
109 return super(EntityAdmin, self).formfield_for_dbfield(db_field, **kwargs)
111 def formfield_for_foreignkeyattribute(self, db_field, request=None, **kwargs):
112 """Get a form field for a ForeignKeyAttribute field."""
113 db = kwargs.get('using')
114 if db_field.name in self.raw_id_fields:
115 kwargs['widget'] = admin.widgets.ForeignKeyRawIdWidget(db_field, db)
116 #TODO: Add support for radio fields
117 #elif db_field.name in self.radio_fields:
118 # kwargs['widget'] = widgets.AdminRadioSelect(attrs={
119 # 'class': get_ul_class(self.radio_fields[db_field.name]),
121 # kwargs['empty_label'] = db_field.blank and _('None') or None
123 return db_field.formfield(**kwargs)
125 def formfield_for_manytomanyattribute(self, db_field, request=None, **kwargs):
126 """Get a form field for a ManyToManyAttribute field."""
127 db = kwargs.get('using')
129 if db_field.name in self.raw_id_fields:
130 kwargs['widget'] = admin.widgets.ManyToManyRawIdWidget(db_field, using=db)
131 kwargs['help_text'] = ''
132 #TODO: Add support for filtered fields.
133 #elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
134 # kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
136 return db_field.formfield(**kwargs)
139 class TreeAdmin(MPTTModelAdmin):
143 class TreeEntityAdmin(EntityAdmin, TreeAdmin):
147 class TagAdmin(admin.ModelAdmin):
148 list_display = ('name', 'slug')
149 prepopulated_fields = {"slug": ("name",)}
150 search_fields = ["name"]
152 def response_add(self, request, obj, post_url_continue='../%s/'):
153 # If it's an ajax request, return a json response containing the necessary information.
154 if request.is_ajax():
155 return HttpResponse(json.dumps({'pk': escape(obj._get_pk_val()), 'unicode': escape(obj)}))
156 return super(TagAdmin, self).response_add(request, obj, post_url_continue)
159 class AddTagAdmin(admin.ModelAdmin):
160 def formfield_for_manytomany(self, db_field, request=None, **kwargs):
162 Get a form Field for a ManyToManyField.
164 # If it uses an intermediary model that isn't auto created, don't show
166 if not db_field.rel.through._meta.auto_created:
169 if db_field.rel.to == Tag and db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
171 if request.user.has_perm(opts.app_label + '.' + opts.get_add_permission()):
172 kwargs['widget'] = TagFilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
173 return db_field.formfield(**kwargs)
175 return super(AddTagAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
178 admin.site.register(Tag, TagAdmin)