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