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 philo.models import Tag, Attribute
8 from philo.models.fields.entities import ForeignKeyAttribute, ManyToManyAttribute
9 from philo.admin.forms.attributes import AttributeForm, AttributeInlineFormSet
10 from philo.admin.widgets import TagFilteredSelectMultiple
11 from philo.forms.entities import EntityForm, proxy_fields_for_entity_model
12 from mptt.admin import MPTTModelAdmin
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 TreeAdmin(MPTTModelAdmin):
142 class TreeEntityAdmin(EntityAdmin, TreeAdmin):
146 class TagAdmin(admin.ModelAdmin):
147 list_display = ('name', 'slug')
148 prepopulated_fields = {"slug": ("name",)}
149 search_fields = ["name"]
151 def response_add(self, request, obj, post_url_continue='../%s/'):
152 # If it's an ajax request, return a json response containing the necessary information.
153 if request.is_ajax():
154 return HttpResponse(json.dumps({'pk': escape(obj._get_pk_val()), 'unicode': escape(obj)}))
155 return super(TagAdmin, self).response_add(request, obj, post_url_continue)
158 class AddTagAdmin(admin.ModelAdmin):
159 def formfield_for_manytomany(self, db_field, request=None, **kwargs):
161 Get a form Field for a ManyToManyField.
163 # If it uses an intermediary model that isn't auto created, don't show
165 if not db_field.rel.through._meta.auto_created:
168 if db_field.rel.to == Tag and db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
170 if request.user.has_perm(opts.app_label + '.' + opts.get_add_permission()):
171 kwargs['widget'] = TagFilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
172 return db_field.formfield(**kwargs)
174 return super(AddTagAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
177 admin.site.register(Tag, TagAdmin)