Minor correction to ContainerContext.get_references().
[philo.git] / philo / admin / base.py
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
8
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
14
15
16 COLLAPSE_CLASSES = ('collapse', 'collapse-closed', 'closed',)
17
18
19 class AttributeInline(generic.GenericTabularInline):
20         ct_field = 'entity_content_type'
21         ct_fk_field = 'entity_object_id'
22         model = Attribute
23         extra = 1
24         allow_add = True
25         classes = COLLAPSE_CLASSES
26         form = AttributeForm
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'
31         else:
32                 template = 'admin/philo/edit_inline/tabular_attribute.html'
33
34
35 # HACK to bypass model validation for proxy fields
36 class SpoofedHiddenFields(object):
37         def __init__(self, proxy_fields, value):
38                 self.value = value
39                 self.spoofed = list(set(value) - set(proxy_fields))
40         
41         def __get__(self, instance, owner):
42                 if instance is None:
43                         return self.spoofed
44                 return self.value
45
46
47 class SpoofedAddedFields(SpoofedHiddenFields):
48         def __init__(self, proxy_fields, value):
49                 self.value = value
50                 self.spoofed = list(set(value) | set(proxy_fields))
51
52
53 def hide_proxy_fields(cls, attname):
54         val = getattr(cls, attname, [])
55         proxy_fields = getattr(cls, 'proxy_fields')
56         if val:
57                 setattr(cls, attname, SpoofedHiddenFields(proxy_fields, val))
58
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))
63
64
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')
70                 return new_class
71 # END HACK
72
73 class EntityAdmin(admin.ModelAdmin):
74         __metaclass__ = EntityAdminMetaclass
75         form = EntityForm
76         inlines = [AttributeInline]
77         save_on_top = True
78         proxy_fields = []
79         
80         def formfield_for_dbfield(self, db_field, **kwargs):
81                 """
82                 Override the default behavior to provide special formfields for EntityEntitys.
83                 Essentially clones the ForeignKey/ManyToManyField special behavior for the Attribute versions.
84                 """
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
90                         # always win.
91                         if db_field.__class__ in self.formfield_overrides:
92                                 kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs)
93                         
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)
99                         
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)
107                         
108                         return formfield
109                 return super(EntityAdmin, self).formfield_for_dbfield(db_field, **kwargs)
110         
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]),
120                 #       })
121                 #       kwargs['empty_label'] = db_field.blank and _('None') or None
122                 
123                 return db_field.formfield(**kwargs)
124         
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')
128                 
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))
135                 
136                 return db_field.formfield(**kwargs)
137
138
139 class TreeEntityAdmin(EntityAdmin, MPTTModelAdmin):
140         pass
141
142
143 class TagAdmin(admin.ModelAdmin):
144         list_display = ('name', 'slug')
145         prepopulated_fields = {"slug": ("name",)}
146         search_fields = ["name"]
147         
148         def response_add(self, request, obj, post_url_continue='../%s/'):
149                 # If it's an ajax request, return a json response containing the necessary information.
150                 if request.is_ajax():
151                         return HttpResponse(json.dumps({'pk': escape(obj._get_pk_val()), 'unicode': escape(obj)}))
152                 return super(TagAdmin, self).response_add(request, obj, post_url_continue)
153
154
155 class AddTagAdmin(admin.ModelAdmin):
156         def formfield_for_manytomany(self, db_field, request=None, **kwargs):
157                 """
158                 Get a form Field for a ManyToManyField.
159                 """
160                 # If it uses an intermediary model that isn't auto created, don't show
161                 # a field in admin.
162                 if not db_field.rel.through._meta.auto_created:
163                         return None
164                 
165                 if db_field.rel.to == Tag and db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
166                         opts = Tag._meta
167                         if request.user.has_perm(opts.app_label + '.' + opts.get_add_permission()):
168                                 kwargs['widget'] = TagFilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
169                                 return db_field.formfield(**kwargs)
170                 
171                 return super(AddTagAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
172
173
174 admin.site.register(Tag, TagAdmin)