3ba9e12b81a82603a373555dd0583c145233e9e6
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / savoirs / admin.py
1 # -*- encoding: utf-8 -*-
2 import re
3
4 from django.db import models
5 from django.contrib import admin
6 from django.contrib.auth.admin import UserAdmin
7 from django.contrib.auth.models import User
8 from django.contrib.admin.filterspecs import RelatedFilterSpec, FilterSpec
9 from django.utils.safestring import mark_safe
10 from django.utils.translation import ugettext as _
11 from django.utils.encoding import smart_unicode, iri_to_uri
12 from django.http import HttpResponseRedirect
13
14 from models import SourceActualite, Actualite, Discipline, Evenement, Record, ListSet, HarvestLog, Profile
15 from savoirs.globals import META
16
17 admin.site.register(Actualite)
18 admin.site.register(SourceActualite)
19 admin.site.register(Evenement)
20
21 class ListSetFilterSpec(RelatedFilterSpec):
22 """
23 Filtre custom automatiquement lié à un field nommé 'listsets'. Il a pour but de s'afficher
24 lorsqu'un server a déjà été présélectionné. Dans ce cas, il affiche une liste qui contient les
25 listsets de ce server.
26 """
27 def __init__(self, f, request, params, model, model_admin):
28 super(ListSetFilterSpec, self).__init__(f, request, params, model, model_admin)
29 self.server_name = request.GET.get('server', None)
30
31 def has_output(self):
32 return self.server_name is not None
33
34 FilterSpec.filter_specs.insert(0, (lambda f: f.name == 'listsets', ListSetFilterSpec))
35
36 # Ces deux classes permettent d'implémenter la possibilité d'avoir un champs readonly_fields
37 # dans l.administration.
38 # Ce champs est devenu natif à partir de la version 1.2
39 # http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields
40 from django import forms
41 class ReadOnlyWidget(forms.Widget):
42 def __init__(self, original_value, display_value):
43 self.original_value = original_value
44 self.display_value = display_value
45
46 super(ReadOnlyWidget, self).__init__()
47
48 def render(self, name, value, attrs=None):
49 if self.display_value is not None:
50 output = self.display_value
51 else:
52 output = unicode(self.original_value)
53
54 # pour les relations
55 try:
56 output = ", ".join([ls.name for ls in self.original_value.get_query_set()])
57 except:
58 pass
59
60 is_url = re.match('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', output)
61 if is_url:
62 output = "<a target='_blank' href='%s'>%s</a>" % (output, output)
63
64 return mark_safe(output)
65
66 def value_from_datadict(self, data, files, name):
67 return self.original_value
68
69 class ReadOnlyAdminFields(object):
70 def get_form(self, request, obj=None):
71 form = super(ReadOnlyAdminFields, self).get_form(request, obj)
72
73 if hasattr(self, 'readonly_fields'):
74 for field_name in self.readonly_fields:
75 if field_name in form.base_fields:
76
77 if hasattr(obj, 'get_%s_display' % field_name):
78 display_value = getattr(obj, 'get_%s_display' % field_name)()
79 else:
80 display_value = None
81
82 form.base_fields[field_name].widget = ReadOnlyWidget(getattr(obj, field_name, ''), display_value)
83 form.base_fields[field_name].required = False
84 return form
85
86
87 class RecordAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
88 fields = [
89 'server',
90 'title',
91 'creator',
92 'description',
93 'modified',
94 'identifier',
95 'uri',
96 'source',
97 'contributor',
98 'publisher',
99 'type',
100 'format',
101 'language',
102 'disciplines',
103 'thematiques',
104 'pays',
105 'regions',
106 'validated',
107 ]
108
109 search_fields = []
110 readonly_fields = []
111
112 list_filter = (
113 'validated',
114 'server',
115 'listsets',
116 'pays',
117 'regions',
118 'disciplines',
119 'thematiques',
120 )
121 list_display = (
122 #OAI et extra AUF
123 'title',
124 'subject',
125 '_description',
126 '_uri',
127 #'server',
128 'identifier',
129 #'source',
130 'modified',
131 'creator',
132 #'contributor',
133 #'language',
134 #'publisher',
135 'format',
136 'type',
137
138 #SEP 2 (aucune données récoltées)
139 #'alt_title',
140 #'abstract',
141 #'creation',
142 #'issued',
143 #'isbn',
144 #'orig_lang',
145 'est_complet',
146 'validated',
147 )
148 actions = ['valider_references',
149 'invalider_references',
150 'assigner_pays',
151 'assigner_regions',
152 'assigner_disciplines',
153 'assigner_thematiques']
154
155 # fonctions pour présenter l'information
156 def __init__(self, *args, **kwargs):
157 """Surcharge l'initialisation pour définir les champs de recherche dynamiquement,
158 et les champs en lecture seule uniquement."""
159 self.search_fields = META.keys()
160 self.readonly_fields = META.keys()
161 self.readonly_fields.append('listsets')
162 super(RecordAdmin, self).__init__(*args, **kwargs)
163
164 def est_complet(self, obj):
165 """ """
166 v = obj.est_complet()
167 return '<img src="/admin_media/img/admin/icon-%s.gif" alt="%d"/>' % (('no','yes')[v], v)
168 est_complet.allow_tags = True
169
170 def _uri(self, obj):
171 """ """
172 return "<a target='_blank' href='%s'>%s</a>" % (obj.uri, obj.uri)
173 _uri.allow_tags = True
174
175 def _description(self, obj):
176 """ """
177 max = 140
178 if obj.description is not None and len(obj.description) > max:
179 return "%s..." % obj.description[:max]
180 else:
181 return obj.description
182
183 # actions
184 def valider_references(self, request, queryset):
185 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
186 return HttpResponseRedirect("/admin/confirmation/%s?ids=%s" % ('valider', ",".join(selected)))
187
188 def invalider_references(self, request, queryset):
189 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
190 return HttpResponseRedirect("/admin/confirmation/%s?ids=%s" % ('invalider', ",".join(selected)))
191
192 def assigner_pays(self, request, queryset):
193 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
194 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('pays', ",".join(selected)))
195
196 def assigner_regions(self, request, queryset):
197 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
198 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('regions', ",".join(selected)))
199
200 def assigner_thematiques(self, request, queryset):
201 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
202 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('thematiques', ",".join(selected)))
203
204 def assigner_disciplines(self, request, queryset):
205 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
206 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('disciplines', ",".join(selected)))
207
208 admin.site.register(Record, RecordAdmin)
209
210 class ListSetAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
211 fields = ['spec', 'name', 'server', 'validated' ]
212 list_display = fields
213 readonly_fields = ['spec', 'name', 'server',]
214 list_filter = ('server',)
215
216 admin.site.register(ListSet, ListSetAdmin)
217
218 class HarvestLogAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
219 fields = ['context', 'name', 'added', 'updated', 'processed', 'record']
220 list_display = fields + ['date']
221 admin_order_fields = ['date']
222 search_fields = fields
223 readonly_fields = fields
224 list_filter = ('context',)
225
226 admin.site.register(HarvestLog, HarvestLogAdmin)
227
228 class ProfileInline(admin.TabularInline):
229 model = Profile
230 fk_name = 'user'
231 max_num = 1
232
233 class UserProfileAdmin(UserAdmin):
234 inlines = [ProfileInline, ]
235
236 admin.site.unregister(User)
237 admin.site.register(User, UserProfileAdmin)
238