All of my work from commits: dd4a194, 692644a, 4a60203, 5de46bc, 152042d, 64a2d4e...
[philo.git] / 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 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
13
14
15 COLLAPSE_CLASSES = ('collapse', 'collapse-closed', 'closed',)
16
17
18 class AttributeInline(generic.GenericTabularInline):
19         ct_field = 'entity_content_type'
20         ct_fk_field = 'entity_object_id'
21         model = Attribute
22         extra = 1
23         allow_add = True
24         classes = COLLAPSE_CLASSES
25         form = AttributeForm
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'
30         else:
31                 template = 'admin/philo/edit_inline/tabular_attribute.html'
32
33
34 def hide_proxy_fields(cls, attname, proxy_field_set):
35         val_set = set(getattr(cls, attname))
36         if proxy_field_set & val_set:
37                 cls._hidden_attributes[attname] = list(val_set)
38                 setattr(cls, attname, list(val_set - proxy_field_set))
39
40
41 class EntityAdminMetaclass(admin.ModelAdmin.__metaclass__):
42         def __new__(cls, name, bases, attrs):
43                 # HACK to bypass model validation for proxy fields by masking them as readonly fields
44                 new_class = super(EntityAdminMetaclass, cls).__new__(cls, name, bases, attrs)
45                 form = getattr(new_class, 'form', None)
46                 if form:
47                         opts = form._meta
48                         if issubclass(form, EntityForm) and opts.model:
49                                 proxy_fields = proxy_fields_for_entity_model(opts.model).keys()
50                                 
51                                 # Store readonly fields iff they have been declared.
52                                 if 'readonly_fields' in attrs or not hasattr(new_class, '_real_readonly_fields'):
53                                         new_class._real_readonly_fields = new_class.readonly_fields
54                                 
55                                 readonly_fields = new_class.readonly_fields
56                                 new_class.readonly_fields = list(set(readonly_fields) | set(proxy_fields))
57                                 
58                                 # Additional HACKS to handle raw_id_fields and other attributes that the admin
59                                 # uses model._meta.get_field to validate.
60                                 new_class._hidden_attributes = {}
61                                 proxy_fields = set(proxy_fields)
62                                 hide_proxy_fields(new_class, 'raw_id_fields', proxy_fields)
63                 #END HACK
64                 return new_class
65
66
67 class EntityAdmin(admin.ModelAdmin):
68         __metaclass__ = EntityAdminMetaclass
69         form = EntityForm
70         inlines = [AttributeInline]
71         save_on_top = True
72         
73         def __init__(self, *args, **kwargs):
74                 # HACK PART 2 restores the actual readonly fields etc. on __init__.
75                 if hasattr(self, '_real_readonly_fields'):
76                         self.readonly_fields = self.__class__._real_readonly_fields
77                 if hasattr(self, '_hidden_attributes'):
78                         for name, value in self._hidden_attributes.items():
79                                 setattr(self, name, value)
80                 # END HACK
81                 super(EntityAdmin, self).__init__(*args, **kwargs)
82         
83         def formfield_for_dbfield(self, db_field, **kwargs):
84                 """
85                 Override the default behavior to provide special formfields for EntityEntitys.
86                 Essentially clones the ForeignKey/ManyToManyField special behavior for the Attribute versions.
87                 """
88                 if not db_field.choices and isinstance(db_field, (ForeignKeyAttribute, ManyToManyAttribute)):
89                         request = kwargs.pop("request", None)
90                         # Combine the field kwargs with any options for formfield_overrides.
91                         # Make sure the passed in **kwargs override anything in
92                         # formfield_overrides because **kwargs is more specific, and should
93                         # always win.
94                         if db_field.__class__ in self.formfield_overrides:
95                                 kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs)
96                         
97                         # Get the correct formfield.
98                         if isinstance(db_field, ManyToManyAttribute):
99                                 formfield = self.formfield_for_manytomanyattribute(db_field, request, **kwargs)
100                         elif isinstance(db_field, ForeignKeyAttribute):
101                                 formfield = self.formfield_for_foreignkeyattribute(db_field, request, **kwargs)
102                         
103                         # For non-raw_id fields, wrap the widget with a wrapper that adds
104                         # extra HTML -- the "add other" interface -- to the end of the
105                         # rendered output. formfield can be None if it came from a
106                         # OneToOneField with parent_link=True or a M2M intermediary.
107                         # TODO: Implement this.
108                         #if formfield and db_field.name not in self.raw_id_fields:
109                         #       formfield.widget = admin.widgets.RelatedFieldWidgetWrapper(formfield.widget, db_field, self.admin_site)
110                         
111                         return formfield
112                 return super(EntityAdmin, self).formfield_for_dbfield(db_field, **kwargs)
113         
114         def formfield_for_foreignkeyattribute(self, db_field, request=None, **kwargs):
115                 """Get a form field for a ForeignKeyAttribute field."""
116                 db = kwargs.get('using')
117                 if db_field.name in self.raw_id_fields:
118                         kwargs['widget'] = admin.widgets.ForeignKeyRawIdWidget(db_field, db)
119                 #TODO: Add support for radio fields
120                 #elif db_field.name in self.radio_fields:
121                 #       kwargs['widget'] = widgets.AdminRadioSelect(attrs={
122                 #               'class': get_ul_class(self.radio_fields[db_field.name]),
123                 #       })
124                 #       kwargs['empty_label'] = db_field.blank and _('None') or None
125                 
126                 return db_field.formfield(**kwargs)
127         
128         def formfield_for_manytomanyattribute(self, db_field, request=None, **kwargs):
129                 """Get a form field for a ManyToManyAttribute field."""
130                 db = kwargs.get('using')
131                 
132                 if db_field.name in self.raw_id_fields:
133                         kwargs['widget'] = admin.widgets.ManyToManyRawIdWidget(db_field, using=db)
134                         kwargs['help_text'] = ''
135                 #TODO: Add support for filtered fields.
136                 #elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
137                 #       kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
138                 
139                 return db_field.formfield(**kwargs)
140
141
142 class TreeAdmin(MPTTModelAdmin):
143         pass
144
145
146 class TreeEntityAdmin(EntityAdmin, TreeAdmin):
147         pass
148
149
150 class TagAdmin(admin.ModelAdmin):
151         list_display = ('name', 'slug')
152         prepopulated_fields = {"slug": ("name",)}
153         search_fields = ["name"]
154         
155         def response_add(self, request, obj, post_url_continue='../%s/'):
156                 # If it's an ajax request, return a json response containing the necessary information.
157                 if request.is_ajax():
158                         return HttpResponse(json.dumps({'pk': escape(obj._get_pk_val()), 'unicode': escape(obj)}))
159                 return super(TagAdmin, self).response_add(request, obj, post_url_continue)
160
161
162 class AddTagAdmin(admin.ModelAdmin):
163         def formfield_for_manytomany(self, db_field, request=None, **kwargs):
164                 """
165                 Get a form Field for a ManyToManyField.
166                 """
167                 # If it uses an intermediary model that isn't auto created, don't show
168                 # a field in admin.
169                 if not db_field.rel.through._meta.auto_created:
170                         return None
171                 
172                 if db_field.rel.to == Tag and db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
173                         opts = Tag._meta
174                         if request.user.has_perm(opts.app_label + '.' + opts.get_add_permission()):
175                                 kwargs['widget'] = TagFilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
176                                 return db_field.formfield(**kwargs)
177                 
178                 return super(AddTagAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
179
180
181 admin.site.register(Tag, TagAdmin)