ca80aa05da4e1cb2dd1bf247d7cfadaa2bf7ac2b
[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(Discipline)
20 admin.site.register(Evenement)
21
22 class 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
35 FilterSpec.filter_specs.insert(0, (lambda f: f.name == 'listsets', ListSetFilterSpec))
36
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
41 from django import forms
42 class 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
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
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)
64
65 return mark_safe(output)
66
67 def value_from_datadict(self, data, files, name):
68 return self.original_value
69
70 class 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
87
88 class RecordAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
89 fields = [
90 'server',
91 'title',
92 'creator',
93 'description',
94 'modified',
95 'identifier',
96 'uri',
97 'source',
98 'contributor',
99 'publisher',
100 'type',
101 'format',
102 'language',
103 'disciplines',
104 'thematiques',
105 'pays',
106 'regions',
107 'validated',
108 ]
109
110 search_fields = []
111 readonly_fields = []
112
113 list_filter = (
114 'validated',
115 'server',
116 'listsets',
117 'pays',
118 'regions',
119 'disciplines',
120 'thematiques',
121 )
122 list_display = (
123 #OAI et extra AUF
124 'title',
125 'subject',
126 '_description',
127 '_uri',
128 #'server',
129 'identifier',
130 #'source',
131 'modified',
132 'creator',
133 #'contributor',
134 #'language',
135 #'publisher',
136 'format',
137 'type',
138
139 #SEP 2 (aucune données récoltées)
140 #'alt_title',
141 #'abstract',
142 #'creation',
143 #'issued',
144 #'isbn',
145 #'orig_lang',
146 'est_complet',
147 'validated',
148 )
149 actions = ['valider_references',
150 'invalider_references',
151 'assigner_pays',
152 'assigner_regions',
153 'assigner_disciplines',
154 'assigner_thematiques']
155
156 # fonctions pour présenter l'information
157 def __init__(self, *args, **kwargs):
158 """Surcharge l'initialisation pour définir les champs de recherche dynamiquement,
159 et les champs en lecture seule uniquement."""
160 self.search_fields = META.keys()
161 self.readonly_fields = META.keys()
162 self.readonly_fields.append('listsets')
163 super(RecordAdmin, self).__init__(*args, **kwargs)
164
165 def est_complet(self, obj):
166 """ """
167 v = obj.est_complet()
168 return '<img src="/admin_media/img/admin/icon-%s.gif" alt="%d"/>' % (('no','yes')[v], v)
169 est_complet.allow_tags = True
170
171 def _uri(self, obj):
172 """ """
173 return "<a target='_blank' href='%s'>%s</a>" % (obj.uri, obj.uri)
174 _uri.allow_tags = True
175
176 def _description(self, obj):
177 """ """
178 max = 140
179 if obj.description is not None and len(obj.description) > max:
180 return "%s..." % obj.description[:max]
181 else:
182 return obj.description
183
184 # actions
185 def valider_references(self, request, queryset):
186 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
187 return HttpResponseRedirect("/admin/confirmation/%s?ids=%s" % ('valider', ",".join(selected)))
188
189 def invalider_references(self, request, queryset):
190 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
191 return HttpResponseRedirect("/admin/confirmation/%s?ids=%s" % ('invalider', ",".join(selected)))
192
193 def assigner_pays(self, request, queryset):
194 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
195 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('pays', ",".join(selected)))
196
197 def assigner_regions(self, request, queryset):
198 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
199 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('regions', ",".join(selected)))
200
201 def assigner_thematiques(self, request, queryset):
202 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
203 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('thematiques', ",".join(selected)))
204
205 def assigner_disciplines(self, request, queryset):
206 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
207 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('disciplines', ",".join(selected)))
208
209 admin.site.register(Record, RecordAdmin)
210
211 class ListSetAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
212 fields = ['spec', 'name', 'server', 'validated' ]
213 list_display = fields
214 readonly_fields = ['spec', 'name', 'server',]
215 list_filter = ('server',)
216
217 admin.site.register(ListSet, ListSetAdmin)
218
219 class HarvestLogAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
220 fields = ['context', 'name', 'added', 'updated', 'processed', 'record']
221 list_display = fields + ['date']
222 admin_order_fields = ['date']
223 search_fields = fields
224 readonly_fields = fields
225 list_filter = ('context',)
226
227 admin.site.register(HarvestLog, HarvestLogAdmin)
228
229 class ProfileInline(admin.TabularInline):
230 model = Profile
231 fk_name = 'user'
232 max_num = 1
233
234 class UserProfileAdmin(UserAdmin):
235 inlines = [ProfileInline, ]
236
237 admin.site.unregister(User)
238 admin.site.register(User, UserProfileAdmin)
239