Merge branch 'master' of git://github.com/melinath/philo
[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 # HACK to bypass model validation for proxy fields
35 class SpoofedHiddenFields(object):
36         def __init__(self, proxy_fields, value):
37                 self.value = value
38                 self.spoofed = list(set(value) - set(proxy_fields))
39         
40         def __get__(self, instance, owner):
41                 if instance is None:
42                         return self.spoofed
43                 return self.value
44
45
46 class SpoofedAddedFields(SpoofedHiddenFields):
47         def __init__(self, proxy_fields, value):
48                 self.value = value
49                 self.spoofed = list(set(value) | set(proxy_fields))
50
51
52 def hide_proxy_fields(cls, attname):
53         val = getattr(cls, attname, [])
54         proxy_fields = getattr(cls, 'proxy_fields')
55         if val:
56                 setattr(cls, attname, SpoofedHiddenFields(proxy_fields, val))
57
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))
62
63
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')
69                 return new_class
70 # END HACK
71
72 class EntityAdmin(admin.ModelAdmin):
73         __metaclass__ = EntityAdminMetaclass
74         form = EntityForm
75         inlines = [AttributeInline]
76         save_on_top = True
77         proxy_fields = []
78         
79         def formfield_for_dbfield(self, db_field, **kwargs):
80                 """
81                 Override the default behavior to provide special formfields for EntityEntitys.
82                 Essentially clones the ForeignKey/ManyToManyField special behavior for the Attribute versions.
83                 """
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
89                         # always win.
90                         if db_field.__class__ in self.formfield_overrides:
91                                 kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs)
92                         
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)
98                         
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)
106                         
107                         return formfield
108                 return super(EntityAdmin, self).formfield_for_dbfield(db_field, **kwargs)
109         
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]),
119                 #       })
120                 #       kwargs['empty_label'] = db_field.blank and _('None') or None
121                 
122                 return db_field.formfield(**kwargs)
123         
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')
127                 
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))
134                 
135                 return db_field.formfield(**kwargs)
136
137
138 class TreeAdmin(MPTTModelAdmin):
139         pass
140
141
142 class TreeEntityAdmin(EntityAdmin, TreeAdmin):
143         pass
144
145
146 class TagAdmin(admin.ModelAdmin):
147         list_display = ('name', 'slug')
148         prepopulated_fields = {"slug": ("name",)}
149         search_fields = ["name"]
150         
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)
156
157
158 class AddTagAdmin(admin.ModelAdmin):
159         def formfield_for_manytomany(self, db_field, request=None, **kwargs):
160                 """
161                 Get a form Field for a ManyToManyField.
162                 """
163                 # If it uses an intermediary model that isn't auto created, don't show
164                 # a field in admin.
165                 if not db_field.rel.through._meta.auto_created:
166                         return None
167                 
168                 if db_field.rel.to == Tag and db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
169                         opts = Tag._meta
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)
173                 
174                 return super(AddTagAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
175
176
177 admin.site.register(Tag, TagAdmin)