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