Merge branch 'master' into cleanup
[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 models import *
11
12
13 class AttributeInline(generic.GenericTabularInline):
14         ct_field = 'entity_content_type'
15         ct_fk_field = 'entity_object_id'
16         model = Attribute
17         extra = 1
18         classes = ('collapse-closed',)
19         allow_add = True
20
21
22 class RelationshipInline(generic.GenericTabularInline):
23         ct_field = 'entity_content_type'
24         ct_fk_field = 'entity_object_id'
25         model = Relationship
26         extra = 1
27         classes = ('collapse-closed',)
28         allow_add = True
29
30
31 class EntityAdmin(admin.ModelAdmin):
32         inlines = [AttributeInline, RelationshipInline]
33         save_on_top = True
34
35
36 class CollectionMemberInline(admin.TabularInline):
37         fk_name = 'collection'
38         model = CollectionMember
39         extra = 1
40         classes = ('collapse-closed',)
41         allow_add = True
42
43
44 class CollectionAdmin(admin.ModelAdmin):
45         inlines = [CollectionMemberInline]
46
47
48 class TemplateAdmin(admin.ModelAdmin):
49         prepopulated_fields = {'slug': ('name',)}
50         fieldsets = (
51                 (None, {
52                         'fields': ('parent', 'name', 'slug')
53                 }),
54                 ('Documentation', {
55                         'classes': ('collapse', 'collapse-closed'),
56                         'fields': ('documentation',)
57                 }),
58                 (None, {
59                         'fields': ('code',)
60                 }),
61                 ('Advanced', {
62                         'classes': ('collapse','collapse-closed'),
63                         'fields': ('mimetype',)
64                 }),
65         )
66         save_on_top = True
67         save_as = True
68         list_display = ('__unicode__', 'slug', 'get_path',)
69
70
71 class ModelLookupWidget(forms.TextInput):
72         # is_hidden = False
73         
74         def __init__(self, content_type, attrs=None):
75                 self.content_type = content_type
76                 super(ModelLookupWidget, self).__init__(attrs)
77         
78         def render(self, name, value, attrs=None):
79                 related_url = '../../../%s/%s/' % (self.content_type.app_label, self.content_type.model)
80                 if attrs is None:
81                         attrs = {}
82                 if not attrs.has_key('class'):
83                         attrs['class'] = 'vForeignKeyRawIdAdminField'
84                 output = super(ModelLookupWidget, self).render(name, value, attrs)
85                 output += '<a href="%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);">' % (related_url, name)
86                 output += '<img src="%simg/admin/selector-search.gif" width="16" height="16" alt="%s" />' % (settings.ADMIN_MEDIA_PREFIX, _('Lookup'))
87                 output += '</a>'
88                 if value:
89                         value_class = self.content_type.model_class()
90                         try:
91                                 value_object = value_class.objects.get(pk=value)
92                                 output += '&nbsp;<strong>%s</strong>' % escape(truncate_words(value_object, 14))
93                         except value_class.DoesNotExist:
94                                 pass
95                 return mark_safe(output)
96
97
98 class PageAdmin(EntityAdmin):
99         prepopulated_fields = {'slug': ('title',)}
100         fieldsets = (
101                 (None, {
102                         'fields': ('title', 'template')
103                 }),
104                 ('URL/Tree/Hierarchy', {
105                         'classes': ('collapse', 'collapse-closed'),
106                         'fields': ('parent', 'slug')
107                 }),
108         )
109         list_display = ('title', 'path', 'template')
110         list_filter = ('template',)
111         search_fields = ['title', 'slug', 'contentlets__content']
112         
113         def get_fieldsets(self, request, obj=None, **kwargs):
114                 fieldsets = list(self.fieldsets)
115                 if obj: # if no obj, creating a new page, thus no template set, thus no containers
116                         page = obj
117                         template = page.template
118                         contentlet_containers, contentreference_containers = template.containers
119                         for container_name in contentlet_containers:
120                                 fieldsets.append((('Container: %s' % container_name), {
121                                         'fields': (('contentlet_container_content_%s' % container_name), ('contentlet_container_dynamic_%s' % container_name))
122                                 }))
123                         for container_name, container_content_type in contentreference_containers:
124                                 fieldsets.append((('Container: %s' % container_name), {
125                                         'fields': (('contentreference_container_%s' % container_name),)
126                                 }))
127                 return fieldsets
128         
129         def get_form(self, request, obj=None, **kwargs):
130                 form = super(PageAdmin, self).get_form(request, obj, **kwargs)
131                 if obj: # if no obj, creating a new page, thus no template set, thus no containers
132                         page = obj
133                         template = page.template
134                         contentlet_containers, contentreference_containers = template.containers
135                         for container_name in contentlet_containers:
136                                 initial_content = None
137                                 initial_dynamic = False
138                                 try:
139                                         contentlet = page.contentlets.get(name__exact=container_name)
140                                         initial_content = contentlet.content
141                                         initial_dynamic = contentlet.dynamic
142                                 except Contentlet.DoesNotExist:
143                                         pass
144                                 form.base_fields[('contentlet_container_content_%s' % container_name)] = forms.CharField(label='Content', widget=forms.Textarea(), initial=initial_content, required=False)
145                                 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)
146                         for container_name, container_content_type in contentreference_containers:
147                                 initial_content = None
148                                 try:
149                                         initial_content = page.contentreferences.get(name__exact=container_name, content_type=container_content_type).content.pk
150                                 except ContentReference.DoesNotExist:
151                                         pass
152                                 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())
153                 return form
154         
155         def save_model(self, request, page, form, change):
156                 page.save()
157                 template = page.template
158                 contentlet_containers, contentreference_containers = template.containers
159                 for container_name in contentlet_containers:
160                         if (('contentlet_container_content_%s' % container_name) in form.cleaned_data) and (('contentlet_container_dynamic_%s' % container_name) in form.cleaned_data):
161                                 content = form.cleaned_data[('contentlet_container_content_%s' % container_name)]
162                                 dynamic = form.cleaned_data[('contentlet_container_dynamic_%s' % container_name)]
163                                 contentlet, created = page.contentlets.get_or_create(name=container_name, defaults={'content': content, 'dynamic': dynamic})
164                                 if not created:
165                                         contentlet.content = content
166                                         contentlet.dynamic = dynamic
167                                         contentlet.save()
168                 for container_name, container_content_type in contentreference_containers:
169                         if ('contentreference_container_%s' % container_name) in form.cleaned_data:
170                                 content = form.cleaned_data[('contentreference_container_%s' % container_name)]
171                                 contentreference, created = page.contentreferences.get_or_create(name=container_name, defaults={'content': content})
172                                 if not created:
173                                         contentreference.content = content
174                                         contentreference.save()
175
176 class RedirectAdmin(admin.ModelAdmin):
177         list_display=('slug', 'target', 'status_code',)
178         list_filter=('status_code',)
179
180 admin.site.register(Collection, CollectionAdmin)
181 admin.site.register(Redirect, RedirectAdmin)
182 admin.site.register(File)
183 admin.site.register(Page, PageAdmin)
184 admin.site.register(Template, TemplateAdmin)