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