Merge git://github.com/melinath/philo into melinath
[philo.git] / admin.py
1 from django.contrib import admin
2 from django.contrib.contenttypes import generic
3 from django.contrib.contenttypes.models import ContentType
4 from django import forms
5 from django.conf import settings
6 from django.utils.translation import ugettext as _
7 from django.utils.safestring import mark_safe
8 from django.utils.html import escape
9 from django.utils.text import truncate_words
10 from philo.models import *
11 from django.core.exceptions import ValidationError, ObjectDoesNotExist
12 from validators import TreeParentValidator, TreePositionValidator
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         template = 'admin/philo/edit_inline/tabular_collapse.html'
24         allow_add = True
25
26
27 class RelationshipInline(generic.GenericTabularInline):
28         ct_field = 'entity_content_type'
29         ct_fk_field = 'entity_object_id'
30         model = Relationship
31         extra = 1
32         template = 'admin/philo/edit_inline/tabular_collapse.html'
33         allow_add = True
34
35
36 class EntityAdmin(admin.ModelAdmin):
37         inlines = [AttributeInline, RelationshipInline]
38         save_on_top = True
39
40
41 class CollectionMemberInline(admin.TabularInline):
42         fk_name = 'collection'
43         model = CollectionMember
44         extra = 1
45         classes = COLLAPSE_CLASSES
46         allow_add = True
47         fields = ('member_content_type', 'member_object_id', 'index',)
48
49
50 class CollectionAdmin(admin.ModelAdmin):
51         inlines = [CollectionMemberInline]
52         list_display = ('name', 'description', 'get_count')
53
54
55 class TreeForm(forms.ModelForm):
56         def __init__(self, *args, **kwargs):
57                 super(TreeForm, self).__init__(*args, **kwargs)
58                 instance = self.instance
59                 instance_class=self.get_instance_class()
60                 
61                 if instance_class is not None:
62                         try:
63                                 self.fields['parent'].queryset = instance_class.objects.exclude(id=instance.id)
64                         except ObjectDoesNotExist:
65                                 pass
66                         
67                 self.fields['parent'].validators = [TreeParentValidator(*self.get_validator_args())]
68         
69         def get_instance_class(self):
70                 return self.instance.__class__
71                 
72         def get_validator_args(self):
73                 return [self.instance]
74         
75         def clean(self):
76                 cleaned_data = self.cleaned_data
77                 
78                 try:
79                         parent = cleaned_data['parent']
80                         slug = cleaned_data['slug']
81                         obj_class = self.get_instance_class()
82                         tpv = TreePositionValidator(parent, slug, obj_class)
83                         tpv(self.instance)
84                 except KeyError:
85                         pass
86                 
87                 return cleaned_data
88
89
90 class TemplateAdmin(admin.ModelAdmin):
91         prepopulated_fields = {'slug': ('name',)}
92         fieldsets = (
93                 (None, {
94                         'fields': ('parent', 'name', 'slug')
95                 }),
96                 ('Documentation', {
97                         'classes': COLLAPSE_CLASSES,
98                         'fields': ('documentation',)
99                 }),
100                 (None, {
101                         'fields': ('code',)
102                 }),
103                 ('Advanced', {
104                         'classes': COLLAPSE_CLASSES,
105                         'fields': ('mimetype',)
106                 }),
107         )
108         save_on_top = True
109         save_as = True
110         list_display = ('__unicode__', 'slug', 'get_path',)
111         form = TreeForm
112
113
114 class ModelLookupWidget(forms.TextInput):
115         # is_hidden = False
116         
117         def __init__(self, content_type, attrs=None):
118                 self.content_type = content_type
119                 super(ModelLookupWidget, self).__init__(attrs)
120         
121         def render(self, name, value, attrs=None):
122                 related_url = '../../../%s/%s/' % (self.content_type.app_label, self.content_type.model)
123                 if attrs is None:
124                         attrs = {}
125                 if not attrs.has_key('class'):
126                         attrs['class'] = 'vForeignKeyRawIdAdminField'
127                 output = super(ModelLookupWidget, self).render(name, value, attrs)
128                 output += '<a href="%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);">' % (related_url, name)
129                 output += '<img src="%simg/admin/selector-search.gif" width="16" height="16" alt="%s" />' % (settings.ADMIN_MEDIA_PREFIX, _('Lookup'))
130                 output += '</a>'
131                 if value:
132                         value_class = self.content_type.model_class()
133                         try:
134                                 value_object = value_class.objects.get(pk=value)
135                                 output += '&nbsp;<strong>%s</strong>' % escape(truncate_words(value_object, 14))
136                         except value_class.DoesNotExist:
137                                 pass
138                 return mark_safe(output)
139
140
141 class NodeForm(TreeForm):
142         def get_instance_class(self):
143                 return Node
144                 
145         def get_validator_args(self):
146                 return [self.instance, 'instance']
147
148
149 class PageAdminForm(NodeForm):
150         class Meta:
151                 model=Page
152
153
154 class RedirectAdminForm(NodeForm):
155         class Meta:
156                 model=Redirect
157
158
159 class FileAdminForm(NodeForm):
160         class Meta:
161                 model=File
162
163
164 class NodeAdmin(EntityAdmin):
165         pass
166
167
168 class RedirectAdmin(NodeAdmin):
169         fieldsets = (
170                 (None, {
171                         'fields': ('slug', 'target', 'status_code')
172                 }),
173                 ('URL/Tree/Hierarchy', {
174                         'classes': COLLAPSE_CLASSES,
175                         'fields': ('parent',)
176                 }),
177         )
178         list_display=('slug', 'target', 'path', 'status_code',)
179         list_filter=('status_code',)
180         form = RedirectAdminForm
181
182
183 class FileAdmin(NodeAdmin):
184         prepopulated_fields = {'slug': ('file',)}
185         fieldsets = (
186                 (None, {
187                         'fields': ('file', 'slug', 'mimetype')
188                 }),
189                 ('URL/Tree/Hierarchy', {
190                         'classes': COLLAPSE_CLASSES,
191                         'fields': ('parent',)
192                 }),
193         )
194         form=FileAdminForm
195         list_display=('slug', 'mimetype', 'path', 'file',)
196
197
198 class PageAdmin(NodeAdmin):
199         add_form_template = 'admin/philo/page/add_form.html'
200         prepopulated_fields = {'slug': ('title',)}
201         fieldsets = (
202                 (None, {
203                         'fields': ('title', 'slug', 'template')
204                 }),
205                 ('URL/Tree/Hierarchy', {
206                         'classes': COLLAPSE_CLASSES,
207                         'fields': ('parent',)
208                 }),
209         )
210         list_display = ('title', 'path', 'template')
211         list_filter = ('template',)
212         search_fields = ['title', 'slug', 'contentlets__content']
213         form = PageAdminForm
214         
215         def get_fieldsets(self, request, obj=None, **kwargs):
216                 fieldsets = list(self.fieldsets)
217                 if obj: # if no obj, creating a new page, thus no template set, thus no containers
218                         template = obj.template
219                         if template.documentation:
220                                 fieldsets.append(('Template Documentation', {
221                                         'description': template.documentation
222                                 }))
223                         contentlet_containers, contentreference_containers = template.containers
224                         for container_name in contentlet_containers:
225                                 fieldsets.append((('Container: %s' % container_name), {
226                                         'fields': (('contentlet_container_content_%s' % container_name), ('contentlet_container_dynamic_%s' % container_name))
227                                 }))
228                         for container_name, container_content_type in contentreference_containers:
229                                 fieldsets.append((('Container: %s' % container_name), {
230                                         'fields': (('contentreference_container_%s' % container_name),)
231                                 }))
232                 return fieldsets
233         
234         def get_form(self, request, obj=None, **kwargs):
235                 form = super(PageAdmin, self).get_form(request, obj, **kwargs)
236                 if obj: # if no obj, creating a new page, thus no template set, thus no containers
237                         page = obj
238                         template = page.template
239                         contentlet_containers, contentreference_containers = template.containers
240                         for container_name in contentlet_containers:
241                                 initial_content = None
242                                 initial_dynamic = False
243                                 try:
244                                         contentlet = page.contentlets.get(name__exact=container_name)
245                                         initial_content = contentlet.content
246                                         initial_dynamic = contentlet.dynamic
247                                 except Contentlet.DoesNotExist:
248                                         pass
249                                 form.base_fields[('contentlet_container_content_%s' % container_name)] = forms.CharField(label='Content', widget=forms.Textarea(), initial=initial_content, required=False)
250                                 form.base_fields[('contentlet_container_dynamic_%s' % container_name)] = forms.BooleanField(label='Dynamic', help_text='Specify whether this content contains dynamic template code', initial=initial_dynamic, required=False)
251                         for container_name, container_content_type in contentreference_containers:
252                                 initial_content = None
253                                 try:
254                                         initial_content = page.contentreferences.get(name__exact=container_name, content_type=container_content_type).content.pk
255                                 except ContentReference.DoesNotExist:
256                                         pass
257                                 form.base_fields[('contentreference_container_%s' % container_name)] = forms.ModelChoiceField(label='References', widget=ModelLookupWidget(container_content_type), initial=initial_content, required=False, queryset=container_content_type.model_class().objects.all())
258                 return form
259         
260         def save_model(self, request, page, form, change):
261                 page.save()
262                 template = page.template
263                 contentlet_containers, contentreference_containers = template.containers
264                 for container_name in contentlet_containers:
265                         if (('contentlet_container_content_%s' % container_name) in form.cleaned_data) and (('contentlet_container_dynamic_%s' % container_name) in form.cleaned_data):
266                                 content = form.cleaned_data[('contentlet_container_content_%s' % container_name)]
267                                 dynamic = form.cleaned_data[('contentlet_container_dynamic_%s' % container_name)]
268                                 contentlet, created = page.contentlets.get_or_create(name=container_name, defaults={'content': content, 'dynamic': dynamic})
269                                 if not created:
270                                         contentlet.content = content
271                                         contentlet.dynamic = dynamic
272                                         contentlet.save()
273                 for container_name, container_content_type in contentreference_containers:
274                         if ('contentreference_container_%s' % container_name) in form.cleaned_data:
275                                 content = form.cleaned_data[('contentreference_container_%s' % container_name)]
276                                 if content == None:
277                                         continue
278                                 contentreference, created = page.contentreferences.get_or_create(name=container_name, defaults={'content': content})
279                                 if not created:
280                                         contentreference.content = content
281                                         contentreference.save()
282
283
284 class RedirectAdmin(admin.ModelAdmin):
285         list_display=('slug', 'target', 'path', 'status_code',)
286         list_filter=('status_code',)
287         form = RedirectAdminForm
288
289
290 class FileAdmin(admin.ModelAdmin):
291         form=FileAdminForm
292         list_display=('slug', 'mimetype', 'path', 'file',)
293
294
295 admin.site.register(Collection, CollectionAdmin)
296 admin.site.register(Redirect, RedirectAdmin)
297 admin.site.register(File, FileAdmin)
298 admin.site.register(Page, PageAdmin)
299 admin.site.register(Template, TemplateAdmin)