Merge branch 'dev' of ssh://git.auf/auf_savoirs_en_partage_django into dev
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / savoirs / admin.py
CommitLineData
6ef8ead4 1# -*- encoding: utf-8 -*-
29e2a8fd 2import operator
23b5b3d5 3import re
116db1fd 4
264a3210 5from django.core.urlresolvers import reverse as url
6a6986bc 6from django.db import models
29e2a8fd 7from django.db.models import Q
5212238e 8from django.db.models.query import QuerySet
6ef8ead4 9from django.contrib import admin
6d885e0c 10from django.contrib.auth.admin import UserAdmin
11from django.contrib.auth.models import User
6a6986bc 12from django.contrib.admin.filterspecs import RelatedFilterSpec, FilterSpec
23b5b3d5 13from django.utils.safestring import mark_safe
6a6986bc 14from django.utils.translation import ugettext as _
15from django.utils.encoding import smart_unicode, iri_to_uri
e3c3296e 16from django.http import HttpResponseRedirect
116db1fd 17
f09bc1c6 18from models import SourceActualite, Actualite, Discipline, Evenement, \
656b9c0f 19 Record, RecordCategorie, ListSet, HarvestLog, Profile, PageStatique
23b5b3d5 20from savoirs.globals import META
6ef8ead4 21
6a6986bc 22class ListSetFilterSpec(RelatedFilterSpec):
23 """
24 Filtre custom automatiquement lié à un field nommé 'listsets'. Il a pour but de s'afficher
25 lorsqu'un server a déjà été présélectionné. Dans ce cas, il affiche une liste qui contient les
26 listsets de ce server.
27 """
28 def __init__(self, f, request, params, model, model_admin):
29 super(ListSetFilterSpec, self).__init__(f, request, params, model, model_admin)
30 self.server_name = request.GET.get('server', None)
31
32 def has_output(self):
33 return self.server_name is not None
34
6a6986bc 35FilterSpec.filter_specs.insert(0, (lambda f: f.name == 'listsets', ListSetFilterSpec))
36
23b5b3d5 37# Ces deux classes permettent d'implémenter la possibilité d'avoir un champs readonly_fields
38# dans l.administration.
39# Ce champs est devenu natif à partir de la version 1.2
40# http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields
41from django import forms
42class ReadOnlyWidget(forms.Widget):
43 def __init__(self, original_value, display_value):
44 self.original_value = original_value
45 self.display_value = display_value
46
47 super(ReadOnlyWidget, self).__init__()
48
49 def render(self, name, value, attrs=None):
50 if self.display_value is not None:
51 output = self.display_value
52 else:
53 output = unicode(self.original_value)
54
d972b61d 55 # pour les relations
56 try:
57 output = ", ".join([ls.name for ls in self.original_value.get_query_set()])
58 except:
59 pass
60
23b5b3d5 61 is_url = re.match('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', output)
62 if is_url:
63 output = "<a target='_blank' href='%s'>%s</a>" % (output, output)
d972b61d 64
23b5b3d5 65 return mark_safe(output)
66
67 def value_from_datadict(self, data, files, name):
68 return self.original_value
69
70class ReadOnlyAdminFields(object):
71 def get_form(self, request, obj=None):
72 form = super(ReadOnlyAdminFields, self).get_form(request, obj)
73
74 if hasattr(self, 'readonly_fields'):
75 for field_name in self.readonly_fields:
76 if field_name in form.base_fields:
77
78 if hasattr(obj, 'get_%s_display' % field_name):
79 display_value = getattr(obj, 'get_%s_display' % field_name)()
80 else:
81 display_value = None
82
83 form.base_fields[field_name].widget = ReadOnlyWidget(getattr(obj, field_name, ''), display_value)
84 form.base_fields[field_name].required = False
85 return form
86
5212238e
EMS
87class RecordAdminQuerySet(QuerySet):
88
89 def filter(self, *args, **kwargs):
90 """Gère des filtres supplémentaires pour l'admin.
91
92 C'est la seule façon que j'ai trouvée de contourner les mécanismes
93 de recherche de l'admin."""
94 search = kwargs.pop('admin_search', None)
95 search_titre = kwargs.pop('admin_search_titre', None)
96 search_sujet = kwargs.pop('admin_search_sujet', None)
97 search_description = kwargs.pop('admin_search_description', None)
98 search_auteur = kwargs.pop('admin_search_auteur', None)
99
100 if search:
101 qs = self
102 search_all = not (search_titre or search_description or search_sujet or search_auteur)
103 fields = []
104 if search_titre or search_all:
105 fields += ['title', 'alt_title']
106 if search_description or search_all:
107 fields += ['description', 'abstract']
108 if search_sujet or search_all:
109 fields += ['subject']
110 if search_auteur or search_all:
111 fields += ['creator', 'contributor']
112
113 for bit in search.split():
114 or_queries = [Q(**{field + '__icontains': bit}) for field in fields]
115 qs = qs.filter(reduce(operator.or_, or_queries))
116
117 if args or kwargs:
118 qs = super(RecordAdminQuerySet, qs).filter(*args, **kwargs)
119 return qs
120 else:
121 return super(RecordAdminQuerySet, self).filter(*args, **kwargs)
23b5b3d5 122
123class RecordAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
a5f76eb4
EMS
124 fields = ['server', 'title', 'creator', 'description', 'modified',
125 'identifier', 'uri', 'source', 'contributor', 'publisher',
656b9c0f
PP
126 'type', 'format', 'language', 'categorie', 'disciplines',
127 'thematiques','pays', 'regions', 'validated']
23b5b3d5 128
23b5b3d5 129 readonly_fields = []
da9020f3 130
a5f76eb4 131 list_filter = ('validated', 'server', 'listsets', 'pays', 'regions',
656b9c0f 132 'disciplines', 'thematiques', 'categorie')
18dbd2cf 133 list_display = ('title', 'subject', 'uri_display', 'creator',
656b9c0f 134 'categorie', 'est_complet', 'validated',)
18dbd2cf
EMS
135 list_editable = ('validated',)
136 list_per_page = 25
137
138 actions = ['assigner_pays', 'assigner_regions', 'assigner_disciplines',
656b9c0f 139 'assigner_thematiques', 'assigner_categorie']
da9020f3 140
23b5b3d5 141 def __init__(self, *args, **kwargs):
142 """Surcharge l'initialisation pour définir les champs de recherche dynamiquement,
143 et les champs en lecture seule uniquement."""
23b5b3d5 144 self.readonly_fields = META.keys()
d972b61d 145 self.readonly_fields.append('listsets')
23b5b3d5 146 super(RecordAdmin, self).__init__(*args, **kwargs)
6d885e0c 147
1719bf4e 148 def queryset(self, request):
5212238e 149 return RecordAdminQuerySet(Record)
77b0fac0
EMS
150
151 # Présentation de l'information
18dbd2cf 152
6d885e0c 153 def est_complet(self, obj):
6d885e0c 154 v = obj.est_complet()
155 return '<img src="/admin_media/img/admin/icon-%s.gif" alt="%d"/>' % (('no','yes')[v], v)
156 est_complet.allow_tags = True
18dbd2cf 157 est_complet.short_description = u'complet'
23b5b3d5 158
18dbd2cf 159 def uri_display(self, obj):
da9020f3 160 return "<a target='_blank' href='%s'>%s</a>" % (obj.uri, obj.uri)
18dbd2cf
EMS
161 uri_display.allow_tags = True
162 uri_display.short_description = u'lien'
da9020f3 163
18dbd2cf 164 def description_display(self, obj):
23b5b3d5 165 max = 140
166 if obj.description is not None and len(obj.description) > max:
167 return "%s..." % obj.description[:max]
168 else:
169 return obj.description
18dbd2cf 170 description_display.short_description = u'description'
da9020f3 171
18dbd2cf 172 # Actions
2be148fe 173
e3c3296e 174 def assigner_pays(self, request, queryset):
175 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
176 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('pays', ",".join(selected)))
18dbd2cf 177 assigner_pays.short_description = u'Assigner des pays'
e3c3296e 178
179 def assigner_regions(self, request, queryset):
180 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
264a3210
EMS
181 return HttpResponseRedirect(url('assigner_regions', kwargs=dict(app_name='savoirs', model_name='record')) + '?ids=' + ','.join(selected))
182 assigner_regions.short_description = u'Assigner des régions'
e3c3296e 183
184 def assigner_thematiques(self, request, queryset):
185 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
186 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('thematiques', ",".join(selected)))
18dbd2cf 187 assigner_thematiques.short_description = u'Assigner des thématiques'
e3c3296e 188
189 def assigner_disciplines(self, request, queryset):
190 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
264a3210
EMS
191 return HttpResponseRedirect(url('assigner_disciplines', kwargs=dict(app_name='savoirs', model_name='record')) + '?ids=' + ','.join(selected))
192 assigner_disciplines.short_description = u'Assigner des disciplines'
116db1fd 193
656b9c0f
PP
194 def assigner_categorie(self, request, queryset):
195 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
196 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('categorie', ",".join(selected)))
197 assigner_categorie.short_description = u'Assigner une catégorie'
198
da9020f3 199admin.site.register(Record, RecordAdmin)
200
d972b61d 201class ListSetAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
9eda5d6c 202 fields = ['spec', 'name', 'server', 'validated' ]
d972b61d 203 list_display = fields
204 readonly_fields = ['spec', 'name', 'server',]
205 list_filter = ('server',)
206
207admin.site.register(ListSet, ListSetAdmin)
208
23b5b3d5 209class HarvestLogAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
a85ba76e 210 fields = ['context', 'name', 'added', 'updated', 'processed', 'record']
23b5b3d5 211 list_display = fields + ['date']
212 admin_order_fields = ['date']
213 search_fields = fields
214 readonly_fields = fields
215 list_filter = ('context',)
216
217admin.site.register(HarvestLog, HarvestLogAdmin)
6d885e0c 218
219class ProfileInline(admin.TabularInline):
220 model = Profile
221 fk_name = 'user'
222 max_num = 1
223
224class UserProfileAdmin(UserAdmin):
225 inlines = [ProfileInline, ]
226
227admin.site.unregister(User)
228admin.site.register(User, UserProfileAdmin)
229
f554ef70 230class ActualiteAdmin(admin.ModelAdmin):
a5f76eb4 231 list_filter = ('visible', 'disciplines', 'regions')
ccbc4363 232 list_display = ('titre', 'source', 'date', 'visible')
011804bb 233 list_editable = ['visible']
264a3210 234 actions = ['rendre_visible', 'rendre_invisible', 'assigner_regions', 'assigner_disciplines']
f554ef70 235
1719bf4e 236 def queryset(self, request):
29e2a8fd 237 return Actualite.all_objects.get_query_set()
1719bf4e 238
f554ef70 239 # actions
240 def rendre_visible(self, request, queryset):
241 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
242 return HttpResponseRedirect("/admin/confirmation/%s/%s?ids=%s" % ('actualite', 'visible', ",".join(selected)))
243
244 def rendre_invisible(self, request, queryset):
245 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
246 return HttpResponseRedirect("/admin/confirmation/%s/%s?ids=%s" % ('actualite', 'invisible', ",".join(selected)))
247
264a3210
EMS
248 def assigner_regions(self, request, queryset):
249 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
250 return HttpResponseRedirect(url('assigner_regions', kwargs=dict(app_name='savoirs', model_name='actualite')) + '?ids=' + ','.join(selected))
251 assigner_regions.short_description = u'Assigner des régions'
252
253 def assigner_disciplines(self, request, queryset):
254 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
255 return HttpResponseRedirect(url('assigner_disciplines', kwargs=dict(app_name='savoirs', model_name='actualite')) + '?ids=' + ','.join(selected))
256 assigner_disciplines.short_description = u'Assigner des disciplines'
257
f554ef70 258admin.site.register(Actualite, ActualiteAdmin)
b7a741ad 259
db2999fa
EMS
260class SourceActualiteAdmin(admin.ModelAdmin):
261 actions = ['update_sources']
011804bb
EMS
262 list_display = ['nom', 'url', 'type']
263 list_filter = ['type']
db2999fa
EMS
264
265 def update_sources(self, request, queryset):
266 for source in queryset:
267 source.update()
268 update_sources.short_description = u'Mettre à jour les fils sélectionnés'
269
270admin.site.register(SourceActualite, SourceActualiteAdmin)
b7a741ad 271
73309469 272class EvenementAdminForm(forms.ModelForm):
86983865 273 mots_cles = forms.CharField(label='Mots-clés', required=False)
86983865 274
73309469 275 class Meta:
276 model = Evenement
277
278 def clean(self,):
279 cleaned_data = self.cleaned_data
280 debut = cleaned_data.get("debut")
281 fin = cleaned_data.get("fin")
7495bc13 282 if debut and fin and debut > fin:
73309469 283 raise forms.ValidationError("La date de fin ne doit pas être antérieure à la date de début")
284 return cleaned_data
285
b7a741ad 286class EvenementAdmin(admin.ModelAdmin):
73309469 287 form = EvenementAdminForm
a5f76eb4 288 list_filter = ('approuve', 'regions', 'discipline', 'discipline_secondaire')
731ef7ab 289 list_display = ('titre', 'debut', 'fin', 'ville', 'pays', 'approuve')
264a3210 290 fields = ['titre', 'discipline', 'discipline_secondaire', 'mots_cles',
731ef7ab
EMS
291 'type', 'adresse', 'ville', 'pays', 'fuseau', 'debut', 'fin', 'piece_jointe', 'regions',
292 'description', 'prenom', 'nom', 'courriel', 'url', 'approuve']
264a3210
EMS
293 actions = ['assigner_regions', 'assigner_disciplines']
294
1719bf4e 295 def queryset(self, request):
29e2a8fd 296 return Evenement.all_objects.get_query_set()
1719bf4e 297
264a3210
EMS
298 def assigner_regions(self, request, queryset):
299 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
300 return HttpResponseRedirect(url('assigner_regions', kwargs=dict(app_name='savoirs', model_name='evenement')) + '?ids=' + ','.join(selected))
301 assigner_regions.short_description = u'Assigner des régions'
302
303 def assigner_disciplines(self, request, queryset):
304 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
305 return HttpResponseRedirect(url('assigner_disciplines', kwargs=dict(app_name='savoirs', model_name='evenement')) + '?ids=' + ','.join(selected))
306 assigner_disciplines.short_description = u'Assigner des disciplines'
b7a741ad 307
308admin.site.register(Evenement, EvenementAdmin)
309
f09bc1c6
EMS
310class PageStatiqueAdmin(admin.ModelAdmin):
311 list_display = ['titre', 'id']
312 list_display_links = ['titre', 'id']
b7a741ad 313
f09bc1c6
EMS
314 class Media:
315 js = ['js/tiny_mce/tiny_mce.js', 'js/tiny_mce_textareas.js']
316
317admin.site.register(PageStatique, PageStatiqueAdmin)
b7a741ad 318
656b9c0f
PP
319
320admin.site.register(RecordCategorie)