9fc88e07c16ba0eaff96235a1740a023aa0673bc
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / savoirs / admin.py
1 # -*- encoding: utf-8 -*-
2 import operator
3 import re
4
5 from django.core.urlresolvers import reverse as url
6 from django.db import models
7 from django.db.models import Q
8 from django.db.models.query import QuerySet
9 from django.contrib import admin
10 from django.contrib.auth.admin import UserAdmin
11 from django.contrib.auth.models import User
12 from django.contrib.admin.filterspecs import RelatedFilterSpec, FilterSpec
13 from django.utils.safestring import mark_safe
14 from django.utils.translation import ugettext as _
15 from django.utils.encoding import smart_unicode, iri_to_uri
16 from django.http import HttpResponseRedirect
17
18 from models import SourceActualite, Actualite, Discipline, Evenement, Record, ListSet, HarvestLog, Profile
19 from savoirs.globals import META
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 class RecordAdminQuerySet(QuerySet):
87
88 def filter(self, *args, **kwargs):
89 """Gère des filtres supplémentaires pour l'admin.
90
91 C'est la seule façon que j'ai trouvée de contourner les mécanismes
92 de recherche de l'admin."""
93 search = kwargs.pop('admin_search', None)
94 search_titre = kwargs.pop('admin_search_titre', None)
95 search_sujet = kwargs.pop('admin_search_sujet', None)
96 search_description = kwargs.pop('admin_search_description', None)
97 search_auteur = kwargs.pop('admin_search_auteur', None)
98
99 if search:
100 qs = self
101 search_all = not (search_titre or search_description or search_sujet or search_auteur)
102 fields = []
103 if search_titre or search_all:
104 fields += ['title', 'alt_title']
105 if search_description or search_all:
106 fields += ['description', 'abstract']
107 if search_sujet or search_all:
108 fields += ['subject']
109 if search_auteur or search_all:
110 fields += ['creator', 'contributor']
111
112 for bit in search.split():
113 or_queries = [Q(**{field + '__icontains': bit}) for field in fields]
114 qs = qs.filter(reduce(operator.or_, or_queries))
115
116 if args or kwargs:
117 qs = super(RecordAdminQuerySet, qs).filter(*args, **kwargs)
118 return qs
119 else:
120 return super(RecordAdminQuerySet, self).filter(*args, **kwargs)
121
122 class RecordAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
123 fields = ['server', 'title', 'creator', 'description', 'modified',
124 'identifier', 'uri', 'source', 'contributor', 'publisher',
125 'type', 'format', 'language', 'disciplines', 'thematiques',
126 'pays', 'regions', 'validated']
127
128 readonly_fields = []
129
130 list_filter = ('validated', 'server', 'listsets', 'pays', 'regions',
131 'disciplines', 'thematiques')
132 list_display = ('title', 'subject', 'uri_display', 'creator',
133 'est_complet', 'validated',)
134 list_editable = ('validated',)
135 list_per_page = 25
136
137 actions = ['assigner_pays', 'assigner_regions', 'assigner_disciplines',
138 'assigner_thematiques']
139
140 def __init__(self, *args, **kwargs):
141 """Surcharge l'initialisation pour définir les champs de recherche dynamiquement,
142 et les champs en lecture seule uniquement."""
143 self.readonly_fields = META.keys()
144 self.readonly_fields.append('listsets')
145 super(RecordAdmin, self).__init__(*args, **kwargs)
146
147 def queryset(self, request):
148 return RecordAdminQuerySet(Record)
149
150 # Présentation de l'information
151
152 def est_complet(self, obj):
153 v = obj.est_complet()
154 return '<img src="/admin_media/img/admin/icon-%s.gif" alt="%d"/>' % (('no','yes')[v], v)
155 est_complet.allow_tags = True
156 est_complet.short_description = u'complet'
157
158 def uri_display(self, obj):
159 return "<a target='_blank' href='%s'>%s</a>" % (obj.uri, obj.uri)
160 uri_display.allow_tags = True
161 uri_display.short_description = u'lien'
162
163 def description_display(self, obj):
164 max = 140
165 if obj.description is not None and len(obj.description) > max:
166 return "%s..." % obj.description[:max]
167 else:
168 return obj.description
169 description_display.short_description = u'description'
170
171 # Actions
172
173 def assigner_pays(self, request, queryset):
174 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
175 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('pays', ",".join(selected)))
176 assigner_pays.short_description = u'Assigner des pays'
177
178 def assigner_regions(self, request, queryset):
179 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
180 return HttpResponseRedirect(url('assigner_regions', kwargs=dict(app_name='savoirs', model_name='record')) + '?ids=' + ','.join(selected))
181 assigner_regions.short_description = u'Assigner des régions'
182
183 def assigner_thematiques(self, request, queryset):
184 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
185 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('thematiques', ",".join(selected)))
186 assigner_thematiques.short_description = u'Assigner des thématiques'
187
188 def assigner_disciplines(self, request, queryset):
189 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
190 return HttpResponseRedirect(url('assigner_disciplines', kwargs=dict(app_name='savoirs', model_name='record')) + '?ids=' + ','.join(selected))
191 assigner_disciplines.short_description = u'Assigner des disciplines'
192
193 admin.site.register(Record, RecordAdmin)
194
195 class ListSetAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
196 fields = ['spec', 'name', 'server', 'validated' ]
197 list_display = fields
198 readonly_fields = ['spec', 'name', 'server',]
199 list_filter = ('server',)
200
201 admin.site.register(ListSet, ListSetAdmin)
202
203 class HarvestLogAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
204 fields = ['context', 'name', 'added', 'updated', 'processed', 'record']
205 list_display = fields + ['date']
206 admin_order_fields = ['date']
207 search_fields = fields
208 readonly_fields = fields
209 list_filter = ('context',)
210
211 admin.site.register(HarvestLog, HarvestLogAdmin)
212
213 class ProfileInline(admin.TabularInline):
214 model = Profile
215 fk_name = 'user'
216 max_num = 1
217
218 class UserProfileAdmin(UserAdmin):
219 inlines = [ProfileInline, ]
220
221 admin.site.unregister(User)
222 admin.site.register(User, UserProfileAdmin)
223
224 class ActualiteAdmin(admin.ModelAdmin):
225 list_filter = ('visible', 'disciplines', 'regions')
226 list_display = ('titre', 'source', 'date', 'visible')
227 list_editable = ['visible']
228 actions = ['rendre_visible', 'rendre_invisible', 'assigner_regions', 'assigner_disciplines']
229
230 def queryset(self, request):
231 return Actualite.all_objects.get_query_set()
232
233 # actions
234 def rendre_visible(self, request, queryset):
235 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
236 return HttpResponseRedirect("/admin/confirmation/%s/%s?ids=%s" % ('actualite', 'visible', ",".join(selected)))
237
238 def rendre_invisible(self, request, queryset):
239 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
240 return HttpResponseRedirect("/admin/confirmation/%s/%s?ids=%s" % ('actualite', 'invisible', ",".join(selected)))
241
242 def assigner_regions(self, request, queryset):
243 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
244 return HttpResponseRedirect(url('assigner_regions', kwargs=dict(app_name='savoirs', model_name='actualite')) + '?ids=' + ','.join(selected))
245 assigner_regions.short_description = u'Assigner des régions'
246
247 def assigner_disciplines(self, request, queryset):
248 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
249 return HttpResponseRedirect(url('assigner_disciplines', kwargs=dict(app_name='savoirs', model_name='actualite')) + '?ids=' + ','.join(selected))
250 assigner_disciplines.short_description = u'Assigner des disciplines'
251
252 admin.site.register(Actualite, ActualiteAdmin)
253
254 class SourceActualiteAdmin(admin.ModelAdmin):
255 actions = ['update_sources']
256 list_display = ['nom', 'url', 'type']
257 list_filter = ['type']
258
259 def update_sources(self, request, queryset):
260 for source in queryset:
261 source.update()
262 update_sources.short_description = u'Mettre à jour les fils sélectionnés'
263
264 admin.site.register(SourceActualite, SourceActualiteAdmin)
265
266 class EvenementAdminForm(forms.ModelForm):
267 mots_cles = forms.CharField(label='Mots-clés', required=False)
268 lieu = forms.CharField(label='Lieu', required=False)
269
270 class Meta:
271 model = Evenement
272
273 def clean(self,):
274 cleaned_data = self.cleaned_data
275 debut = cleaned_data.get("debut")
276 fin = cleaned_data.get("fin")
277 if debut and fin and debut > fin:
278 raise forms.ValidationError("La date de fin ne doit pas être antérieure à la date de début")
279 return cleaned_data
280
281 class EvenementAdmin(admin.ModelAdmin):
282 form = EvenementAdminForm
283 list_filter = ('approuve', 'regions', 'discipline', 'discipline_secondaire')
284 list_display = ('titre', 'debut', 'fin', 'lieu', 'approuve')
285 fields = ['titre', 'discipline', 'discipline_secondaire', 'mots_cles',
286 'type', 'pays', 'fuseau', 'debut', 'fin', 'lieu', 'piece_jointe', 'regions',
287 'description', 'contact', 'url', 'approuve']
288 actions = ['assigner_regions', 'assigner_disciplines']
289
290 def queryset(self, request):
291 return Evenement.all_objects.get_query_set()
292
293 def assigner_regions(self, request, queryset):
294 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
295 return HttpResponseRedirect(url('assigner_regions', kwargs=dict(app_name='savoirs', model_name='evenement')) + '?ids=' + ','.join(selected))
296 assigner_regions.short_description = u'Assigner des régions'
297
298 def assigner_disciplines(self, request, queryset):
299 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
300 return HttpResponseRedirect(url('assigner_disciplines', kwargs=dict(app_name='savoirs', model_name='evenement')) + '?ids=' + ','.join(selected))
301 assigner_disciplines.short_description = u'Assigner des disciplines'
302
303 admin.site.register(Evenement, EvenementAdmin)
304
305
306