ferme #460 ajout du dashboard pour connaitre les references à traiter
[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 = ['assigner_pays',
150 'assigner_regions',
151 'assigner_disciplines',
152 'assigner_thematiques']
153
154 # fonctions pour présenter l'information
155 def __init__(self, *args, **kwargs):
156 """Surcharge l'initialisation pour définir les champs de recherche dynamiquement,
157 et les champs en lecture seule uniquement."""
158 self.search_fields = META.keys()
159 self.readonly_fields = META.keys()
160 self.readonly_fields.append('listsets')
161 super(RecordAdmin, self).__init__(*args, **kwargs)
162
163 def est_complet(self, obj):
164 """ """
165 v = obj.est_complet()
166 return '<img src="/admin_media/img/admin/icon-%s.gif" alt="%d"/>' % (('no','yes')[v], v)
167 est_complet.allow_tags = True
168
169 def _uri(self, obj):
170 """ """
171 return "<a target='_blank' href='%s'>%s</a>" % (obj.uri, obj.uri)
172 _uri.allow_tags = True
173
174 def _description(self, obj):
175 """ """
176 max = 140
177 if obj.description is not None and len(obj.description) > max:
178 return "%s..." % obj.description[:max]
179 else:
180 return obj.description
181
182 # actions
183 def assigner_pays(self, request, queryset):
184 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
185 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('pays', ",".join(selected)))
186
187 def assigner_regions(self, request, queryset):
188 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
189 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('regions', ",".join(selected)))
190
191 def assigner_thematiques(self, request, queryset):
192 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
193 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('thematiques', ",".join(selected)))
194
195 def assigner_disciplines(self, request, queryset):
196 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
197 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('disciplines', ",".join(selected)))
198
199 admin.site.register(Record, RecordAdmin)
200
201 class ListSetAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
202 fields = ['spec', 'name', 'server', 'validated' ]
203 list_display = fields
204 readonly_fields = ['spec', 'name', 'server',]
205 list_filter = ('server',)
206
207 admin.site.register(ListSet, ListSetAdmin)
208
209 class HarvestLogAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
210 fields = ['context', 'name', 'added', 'updated', 'processed', 'record']
211 list_display = fields + ['date']
212 admin_order_fields = ['date']
213 search_fields = fields
214 readonly_fields = fields
215 list_filter = ('context',)
216
217 admin.site.register(HarvestLog, HarvestLogAdmin)
218
219 class ProfileInline(admin.TabularInline):
220 model = Profile
221 fk_name = 'user'
222 max_num = 1
223
224 class UserProfileAdmin(UserAdmin):
225 inlines = [ProfileInline, ]
226
227 admin.site.unregister(User)
228 admin.site.register(User, UserProfileAdmin)
229