[#3087] Ajouté du support pour le framework de messages
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / savoirs / admin.py
CommitLineData
6ef8ead4 1# -*- encoding: utf-8 -*-
29e2a8fd 2import operator
116db1fd 3
31249cf3 4from django import forms
264a3210 5from django.core.urlresolvers import reverse as url
29e2a8fd 6from django.db.models import Q
5212238e 7from django.db.models.query import QuerySet
6ef8ead4 8from django.contrib import admin
6d885e0c 9from django.contrib.auth.admin import UserAdmin
10from django.contrib.auth.models import User
e3c3296e 11from django.http import HttpResponseRedirect
116db1fd 12
31249cf3
EMS
13from models import \
14 SourceActualite, Actualite, ActualiteVoir, \
15 Evenement, EvenementVoir, Record, RecordEdit, \
16 RecordCategorie, ListSet, HarvestLog, Profile, PageStatique
81fe476e 17
23b5b3d5 18from savoirs.globals import META
6ef8ead4 19
31249cf3
EMS
20
21class ListSetListFilter(admin.RelatedFieldListFilter):
6a6986bc 22 """
31249cf3
EMS
23 Filtre custom automatiquement lié à un field nommé 'listsets'. Il a pour
24 but de s'afficher lorsqu'un server a déjà été présélectionné. Dans ce
25 cas, il affiche une liste qui contient les listsets de ce server.
6a6986bc 26 """
31249cf3
EMS
27 def __init__(self, field, request, params, model, model_admin, field_path):
28 super(ListSetListFilter, self).__init__(
29 field, request, params, model, model_admin, field_path
30 )
6a6986bc 31 self.server_name = request.GET.get('server', None)
32
33 def has_output(self):
34 return self.server_name is not None
35
23b5b3d5 36
5212238e
EMS
37class RecordAdminQuerySet(QuerySet):
38
39 def filter(self, *args, **kwargs):
40 """Gère des filtres supplémentaires pour l'admin.
31249cf3 41
5212238e
EMS
42 C'est la seule façon que j'ai trouvée de contourner les mécanismes
43 de recherche de l'admin."""
44 search = kwargs.pop('admin_search', None)
45 search_titre = kwargs.pop('admin_search_titre', None)
46 search_sujet = kwargs.pop('admin_search_sujet', None)
47 search_description = kwargs.pop('admin_search_description', None)
48 search_auteur = kwargs.pop('admin_search_auteur', None)
49
50 if search:
51 qs = self
31249cf3
EMS
52 search_all = not (search_titre or search_description or
53 search_sujet or search_auteur)
5212238e
EMS
54 fields = []
55 if search_titre or search_all:
56 fields += ['title', 'alt_title']
57 if search_description or search_all:
58 fields += ['description', 'abstract']
59 if search_sujet or search_all:
60 fields += ['subject']
61 if search_auteur or search_all:
62 fields += ['creator', 'contributor']
63
64 for bit in search.split():
31249cf3
EMS
65 or_queries = [Q(**{field + '__icontains': bit})
66 for field in fields]
5212238e
EMS
67 qs = qs.filter(reduce(operator.or_, or_queries))
68
69 if args or kwargs:
70 qs = super(RecordAdminQuerySet, qs).filter(*args, **kwargs)
71 return qs
72 else:
73 return super(RecordAdminQuerySet, self).filter(*args, **kwargs)
23b5b3d5 74
31249cf3
EMS
75
76class RecordAdmin(admin.ModelAdmin):
77 fields = ('server', 'title', 'creator', 'description', 'modified',
a5f76eb4 78 'identifier', 'uri', 'source', 'contributor', 'publisher',
656b9c0f 79 'type', 'format', 'language', 'categorie', 'disciplines',
31249cf3
EMS
80 'thematiques', 'pays', 'regions', 'validated')
81
82 list_filter = (
83 'validated', 'server', ('listsets', ListSetListFilter), 'pays',
84 'regions', 'disciplines', 'thematiques', 'categorie'
85 )
86 list_display = (
87 'title', 'subject', 'uri_display', 'creator', 'categorie',
88 'est_complet', 'validated'
89 )
18dbd2cf
EMS
90 list_editable = ('validated',)
91 list_per_page = 25
92
31249cf3
EMS
93 actions = ('assigner_pays', 'assigner_regions', 'assigner_disciplines',
94 'assigner_thematiques', 'assigner_categorie')
da9020f3 95
23b5b3d5 96 def __init__(self, *args, **kwargs):
31249cf3
EMS
97 """
98 Surcharge l'initialisation pour définir les champs de recherche
99 dynamiquement, et les champs en lecture seule uniquement.
100 """
23b5b3d5 101 self.readonly_fields = META.keys()
d972b61d 102 self.readonly_fields.append('listsets')
31249cf3 103 super(RecordAdmin, self).__init__(*args, **kwargs)
6d885e0c 104
1719bf4e 105 def queryset(self, request):
5212238e 106 return RecordAdminQuerySet(Record)
77b0fac0
EMS
107
108 # Présentation de l'information
31249cf3 109
6d885e0c 110 def est_complet(self, obj):
6d885e0c 111 v = obj.est_complet()
31249cf3
EMS
112 return '<img src="/admin_media/img/admin/icon-%s.gif" alt="%d"/>' % (
113 ('no', 'yes')[v], v
114 )
6d885e0c 115 est_complet.allow_tags = True
18dbd2cf 116 est_complet.short_description = u'complet'
31249cf3 117
18dbd2cf 118 def uri_display(self, obj):
da9020f3 119 return "<a target='_blank' href='%s'>%s</a>" % (obj.uri, obj.uri)
18dbd2cf
EMS
120 uri_display.allow_tags = True
121 uri_display.short_description = u'lien'
da9020f3 122
18dbd2cf 123 def description_display(self, obj):
23b5b3d5 124 max = 140
31249cf3 125 if obj.description is not None and len(obj.description) > max:
23b5b3d5 126 return "%s..." % obj.description[:max]
127 else:
128 return obj.description
18dbd2cf 129 description_display.short_description = u'description'
da9020f3 130
18dbd2cf 131 # Actions
2be148fe 132
e3c3296e 133 def assigner_pays(self, request, queryset):
b07400fb
PP
134 selected = queryset.values_list('id', flat=True)
135 selected = ",".join("%s" % val for val in selected)
31249cf3
EMS
136 return HttpResponseRedirect(
137 "/admin/assigner_%s?ids=%s" % ('pays', selected)
138 )
18dbd2cf 139 assigner_pays.short_description = u'Assigner des pays'
e3c3296e 140
141 def assigner_regions(self, request, queryset):
b07400fb
PP
142 selected = queryset.values_list('id', flat=True)
143 selected = ",".join("%s" % val for val in selected)
31249cf3
EMS
144 return HttpResponseRedirect(url(
145 'assigner_regions',
146 kwargs={'app_name': 'savoirs', 'model_name': 'record'}
147 ) + '?ids=' + selected)
264a3210 148 assigner_regions.short_description = u'Assigner des régions'
e3c3296e 149
150 def assigner_thematiques(self, request, queryset):
b07400fb
PP
151 selected = queryset.values_list('id', flat=True)
152 selected = ",".join("%s" % val for val in selected)
31249cf3
EMS
153 return HttpResponseRedirect(
154 "/admin/assigner_%s?ids=%s" % ('thematiques', selected)
155 )
18dbd2cf 156 assigner_thematiques.short_description = u'Assigner des thématiques'
e3c3296e 157
158 def assigner_disciplines(self, request, queryset):
b07400fb
PP
159 selected = queryset.values_list('id', flat=True)
160 selected = ",".join("%s" % val for val in selected)
31249cf3
EMS
161 return HttpResponseRedirect(url(
162 'assigner_disciplines',
163 kwargs={'app_name': 'savoirs', 'model_name': 'record'}
164 ) + '?ids=' + selected)
264a3210 165 assigner_disciplines.short_description = u'Assigner des disciplines'
116db1fd 166
656b9c0f 167 def assigner_categorie(self, request, queryset):
b07400fb
PP
168 selected = queryset.values_list('id', flat=True)
169 selected = ",".join("%s" % val for val in selected)
31249cf3
EMS
170 return HttpResponseRedirect(
171 "/admin/assigner_%s?ids=%s" % ('categorie', selected)
172 )
656b9c0f
PP
173 assigner_categorie.short_description = u'Assigner une catégorie'
174
da9020f3 175admin.site.register(Record, RecordAdmin)
176
927764f9 177
31249cf3
EMS
178class RecordEditAdmin(RecordAdmin):
179 list_editable = ()
4bf80bb5 180 change_list_template = "admin/savoirs/record/change_list.html"
927764f9
PP
181
182 def __init__(self, model, admin_site):
183 super(RecordEditAdmin, self).__init__(model, admin_site)
927764f9
PP
184 self.readonly_fields = self.fields
185
186 def get_actions(self, request):
187 actions = super(RecordEditAdmin, self).get_actions(request)
927764f9
PP
188 del actions['assigner_pays']
189 del actions['assigner_thematiques']
31249cf3 190 del actions['assigner_categorie']
927764f9
PP
191
192 return actions
193
194 def assigner_disciplines(self, request, queryset):
195 selected = queryset.values_list('id', flat=True)
196 selected = ",".join("%s" % val for val in selected)
31249cf3
EMS
197 return HttpResponseRedirect(url(
198 'assigner_disciplines',
199 kwargs={'app_name': 'savoirs', 'model_name': 'recordedit'}
200 ) + '?ids=' + selected)
927764f9
PP
201 assigner_disciplines.short_description = u'Assigner des disciplines'
202
203 def assigner_regions(self, request, queryset):
204 selected = queryset.values_list('id', flat=True)
205 selected = ",".join("%s" % val for val in selected)
31249cf3
EMS
206 return HttpResponseRedirect(url(
207 'assigner_regions',
208 kwargs={'app_name': 'savoirs', 'model_name': 'recordedit'}
209 ) + '?ids=' + selected)
927764f9
PP
210 assigner_regions.short_description = u'Assigner des régions'
211
212admin.site.register(RecordEdit, RecordEditAdmin)
213
214
31249cf3
EMS
215class ListSetAdmin(admin.ModelAdmin):
216 fields = ('spec', 'name', 'server', 'validated')
d972b61d 217 list_display = fields
31249cf3 218 readonly_fields = ('spec', 'name', 'server')
d972b61d 219 list_filter = ('server',)
220
221admin.site.register(ListSet, ListSetAdmin)
222
31249cf3
EMS
223
224class HarvestLogAdmin(admin.ModelAdmin):
225 fields = ('context', 'name', 'added', 'updated', 'processed', 'record')
226 list_display = fields + ('date',)
227 admin_order_fields = ('date',)
228 search_fields = (
229 'context', 'name', 'added', 'updated', 'processed', 'record__title'
230 )
23b5b3d5 231 readonly_fields = fields
232 list_filter = ('context',)
233
234admin.site.register(HarvestLog, HarvestLogAdmin)
6d885e0c 235
31249cf3 236
6d885e0c 237class ProfileInline(admin.TabularInline):
238 model = Profile
239 fk_name = 'user'
240 max_num = 1
241
31249cf3 242
6d885e0c 243class UserProfileAdmin(UserAdmin):
31249cf3 244 inlines = (ProfileInline,)
6d885e0c 245
246admin.site.unregister(User)
247admin.site.register(User, UserProfileAdmin)
248
31249cf3 249
f554ef70 250class ActualiteAdmin(admin.ModelAdmin):
a5f76eb4 251 list_filter = ('visible', 'disciplines', 'regions')
ccbc4363 252 list_display = ('titre', 'source', 'date', 'visible')
31249cf3
EMS
253 list_editable = ('visible',)
254 actions = (
255 'rendre_visible', 'rendre_invisible', 'assigner_regions',
256 'assigner_disciplines'
257 )
f554ef70 258
1719bf4e 259 def queryset(self, request):
29e2a8fd 260 return Actualite.all_objects.get_query_set()
1719bf4e 261
f554ef70 262 # actions
263 def rendre_visible(self, request, queryset):
b07400fb
PP
264 selected = queryset.values_list('id', flat=True)
265 selected = ",".join("%s" % val for val in selected)
31249cf3
EMS
266 return HttpResponseRedirect(
267 "/admin/confirmation/%s/%s?ids=%s" %
268 ('actualite', 'visible', selected)
269 )
f554ef70 270
271 def rendre_invisible(self, request, queryset):
b07400fb
PP
272 selected = queryset.values_list('id', flat=True)
273 selected = ",".join("%s" % val for val in selected)
31249cf3
EMS
274 return HttpResponseRedirect(
275 "/admin/confirmation/%s/%s?ids=%s" %
276 ('actualite', 'invisible', selected)
277 )
f554ef70 278
264a3210 279 def assigner_regions(self, request, queryset):
b07400fb
PP
280 selected = queryset.values_list('id', flat=True)
281 selected = ",".join("%s" % val for val in selected)
31249cf3
EMS
282 return HttpResponseRedirect(url(
283 'assigner_regions',
284 kwargs={'app_name': 'savoirs', 'model_name': 'actualite'}
285 ) + '?ids=' + selected)
264a3210
EMS
286 assigner_regions.short_description = u'Assigner des régions'
287
288 def assigner_disciplines(self, request, queryset):
b07400fb
PP
289 selected = queryset.values_list('id', flat=True)
290 selected = ",".join("%s" % val for val in selected)
31249cf3
EMS
291 return HttpResponseRedirect(url(
292 'assigner_disciplines',
293 kwargs={'app_name': 'savoirs', 'model_name': 'actualite'}
294 ) + '?ids=' + selected)
264a3210
EMS
295 assigner_disciplines.short_description = u'Assigner des disciplines'
296
f554ef70 297admin.site.register(Actualite, ActualiteAdmin)
b7a741ad 298
31249cf3 299
81fe476e
PP
300class ActualiteVoirAdmin(ActualiteAdmin):
301
302 actions = None
31249cf3
EMS
303 list_editable = ()
304 fields = (
305 'titre', 'texte', 'url', 'date', 'visible', 'ancienid', 'source',
306 'disciplines', 'regions'
307 )
81fe476e
PP
308
309 def __init__(self, model, admin_site):
310 super(ActualiteVoirAdmin, self).__init__(model, admin_site)
81fe476e
PP
311 self.readonly_fields = self.fields
312
313
314admin.site.register(ActualiteVoir, ActualiteVoirAdmin)
315
31249cf3 316
db2999fa 317class SourceActualiteAdmin(admin.ModelAdmin):
31249cf3
EMS
318 actions = ('update_sources',)
319 list_display = ('nom', 'url', 'type')
320 list_filter = ('type',)
db2999fa
EMS
321
322 def update_sources(self, request, queryset):
323 for source in queryset:
324 source.update()
325 update_sources.short_description = u'Mettre à jour les fils sélectionnés'
326
327admin.site.register(SourceActualite, SourceActualiteAdmin)
b7a741ad 328
31249cf3 329
73309469 330class EvenementAdminForm(forms.ModelForm):
86983865 331 mots_cles = forms.CharField(label='Mots-clés', required=False)
86983865 332
73309469 333 class Meta:
334 model = Evenement
335
336 def clean(self,):
337 cleaned_data = self.cleaned_data
338 debut = cleaned_data.get("debut")
339 fin = cleaned_data.get("fin")
7495bc13 340 if debut and fin and debut > fin:
31249cf3
EMS
341 raise forms.ValidationError(
342 "La date de fin ne doit pas être antérieure à la date de début"
343 )
73309469 344 return cleaned_data
345
31249cf3 346
b7a741ad 347class EvenementAdmin(admin.ModelAdmin):
73309469 348 form = EvenementAdminForm
31249cf3
EMS
349 list_filter = (
350 'approuve', 'regions', 'discipline', 'discipline_secondaire'
351 )
731ef7ab 352 list_display = ('titre', 'debut', 'fin', 'ville', 'pays', 'approuve')
31249cf3
EMS
353 fields = ('titre', 'discipline', 'discipline_secondaire', 'mots_cles',
354 'type', 'adresse', 'ville', 'pays', 'fuseau', 'debut', 'fin',
355 'piece_jointe', 'regions', 'description', 'prenom', 'nom',
356 'courriel', 'url', 'approuve')
357 actions = ('assigner_regions', 'assigner_disciplines')
264a3210 358
1719bf4e 359 def queryset(self, request):
29e2a8fd 360 return Evenement.all_objects.get_query_set()
1719bf4e 361
264a3210 362 def assigner_regions(self, request, queryset):
b07400fb
PP
363 selected = queryset.values_list('id', flat=True)
364 selected = ",".join("%s" % val for val in selected)
31249cf3
EMS
365 return HttpResponseRedirect(url(
366 'assigner_regions',
367 kwargs={'app_name': 'savoirs', 'model_name': 'evenement'}
368 ) + '?ids=' + selected)
264a3210
EMS
369 assigner_regions.short_description = u'Assigner des régions'
370
371 def assigner_disciplines(self, request, queryset):
b07400fb
PP
372 selected = queryset.values_list('id', flat=True)
373 selected = ",".join("%s" % val for val in selected)
31249cf3
EMS
374 return HttpResponseRedirect(url(
375 'assigner_disciplines',
376 kwargs={'app_name': 'savoirs', 'model_name': 'evenement'}
377 ) + '?ids=' + selected)
264a3210 378 assigner_disciplines.short_description = u'Assigner des disciplines'
b7a741ad 379
380admin.site.register(Evenement, EvenementAdmin)
381
31249cf3 382
81fe476e
PP
383class EvenementVoirAdmin(EvenementAdmin):
384
385 actions = None
31249cf3 386 list_editable = ()
81fe476e
PP
387
388 def __init__(self, model, admin_site):
389 super(EvenementVoirAdmin, self).__init__(model, admin_site)
81fe476e
PP
390 self.readonly_fields = self.fields
391
81fe476e
PP
392admin.site.register(EvenementVoir, EvenementVoirAdmin)
393
31249cf3 394
f09bc1c6 395class PageStatiqueAdmin(admin.ModelAdmin):
31249cf3
EMS
396 list_display = ('titre', 'id')
397 list_display_links = ('titre', 'id')
b7a741ad 398
f09bc1c6 399 class Media:
31249cf3 400 js = ('js/tiny_mce/tiny_mce.js', 'js/tiny_mce_textareas.js')
f09bc1c6
EMS
401
402admin.site.register(PageStatique, PageStatiqueAdmin)
b7a741ad 403
656b9c0f
PP
404
405admin.site.register(RecordCategorie)