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