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 Attribute
10 from philo.models.fields.entities import ForeignKeyAttribute, ManyToManyAttribute
11 from philo.admin.forms.attributes import AttributeForm, AttributeInlineFormSet
12 from philo.forms.entities import EntityForm, proxy_fields_for_entity_model
15 COLLAPSE_CLASSES = ('collapse', 'collapse-closed', 'closed',)
18 class AttributeInline(generic.GenericTabularInline):
19 ct_field = 'entity_content_type'
20 ct_fk_field = 'entity_object_id'
24 classes = COLLAPSE_CLASSES
26 formset = AttributeInlineFormSet
27 fields = ['key', 'value_content_type']
28 if 'grappelli' in settings.INSTALLED_APPS:
29 template = 'admin/philo/edit_inline/grappelli_tabular_attribute.html'
31 template = 'admin/philo/edit_inline/tabular_attribute.html'
34 # HACK to bypass model validation for proxy fields
35 class SpoofedHiddenFields(object):
36 def __init__(self, proxy_fields, value):
38 self.spoofed = list(set(value) - set(proxy_fields))
40 def __get__(self, instance, owner):
46 class SpoofedAddedFields(SpoofedHiddenFields):
47 def __init__(self, proxy_fields, value):
49 self.spoofed = list(set(value) | set(proxy_fields))
52 def hide_proxy_fields(cls, attname):
53 val = getattr(cls, attname, [])
54 proxy_fields = getattr(cls, 'proxy_fields')
56 setattr(cls, attname, SpoofedHiddenFields(proxy_fields, val))
58 def add_proxy_fields(cls, attname):
59 val = getattr(cls, attname, [])
60 proxy_fields = getattr(cls, 'proxy_fields')
61 setattr(cls, attname, SpoofedAddedFields(proxy_fields, val))
64 class EntityAdminMetaclass(admin.ModelAdmin.__metaclass__):
65 def __new__(cls, name, bases, attrs):
66 new_class = super(EntityAdminMetaclass, cls).__new__(cls, name, bases, attrs)
67 hide_proxy_fields(new_class, 'raw_id_fields')
68 add_proxy_fields(new_class, 'readonly_fields')
72 class EntityAdmin(admin.ModelAdmin):
73 __metaclass__ = EntityAdminMetaclass
75 inlines = [AttributeInline]
79 def formfield_for_dbfield(self, db_field, **kwargs):
81 Override the default behavior to provide special formfields for EntityEntitys.
82 Essentially clones the ForeignKey/ManyToManyField special behavior for the Attribute versions.
84 if not db_field.choices and isinstance(db_field, (ForeignKeyAttribute, ManyToManyAttribute)):
85 request = kwargs.pop("request", None)
86 # Combine the field kwargs with any options for formfield_overrides.
87 # Make sure the passed in **kwargs override anything in
88 # formfield_overrides because **kwargs is more specific, and should
90 if db_field.__class__ in self.formfield_overrides:
91 kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs)
93 # Get the correct formfield.
94 if isinstance(db_field, ManyToManyAttribute):
95 formfield = self.formfield_for_manytomanyattribute(db_field, request, **kwargs)
96 elif isinstance(db_field, ForeignKeyAttribute):
97 formfield = self.formfield_for_foreignkeyattribute(db_field, request, **kwargs)
99 # For non-raw_id fields, wrap the widget with a wrapper that adds
100 # extra HTML -- the "add other" interface -- to the end of the
101 # rendered output. formfield can be None if it came from a
102 # OneToOneField with parent_link=True or a M2M intermediary.
103 # TODO: Implement this.
104 #if formfield and db_field.name not in self.raw_id_fields:
105 # formfield.widget = admin.widgets.RelatedFieldWidgetWrapper(formfield.widget, db_field, self.admin_site)
108 return super(EntityAdmin, self).formfield_for_dbfield(db_field, **kwargs)
110 def formfield_for_foreignkeyattribute(self, db_field, request=None, **kwargs):
111 """Get a form field for a ForeignKeyAttribute field."""
112 db = kwargs.get('using')
113 if db_field.name in self.raw_id_fields:
114 kwargs['widget'] = admin.widgets.ForeignKeyRawIdWidget(db_field, db)
115 #TODO: Add support for radio fields
116 #elif db_field.name in self.radio_fields:
117 # kwargs['widget'] = widgets.AdminRadioSelect(attrs={
118 # 'class': get_ul_class(self.radio_fields[db_field.name]),
120 # kwargs['empty_label'] = db_field.blank and _('None') or None
122 return db_field.formfield(**kwargs)
124 def formfield_for_manytomanyattribute(self, db_field, request=None, **kwargs):
125 """Get a form field for a ManyToManyAttribute field."""
126 db = kwargs.get('using')
128 if db_field.name in self.raw_id_fields:
129 kwargs['widget'] = admin.widgets.ManyToManyRawIdWidget(db_field, using=db)
130 kwargs['help_text'] = ''
131 #TODO: Add support for filtered fields.
132 #elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
133 # kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
135 return db_field.formfield(**kwargs)
138 class TreeEntityAdmin(EntityAdmin, MPTTModelAdmin):