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