a85f657b4c37d8719e3cc1a5658e531fa2aefd7b
[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.admin.filterspecs import RelatedFilterSpec, FilterSpec
7 from django.utils.safestring import mark_safe
8 from django.utils.translation import ugettext as _
9 from django.utils.encoding import smart_unicode, iri_to_uri
10 from django.http import HttpResponseRedirect
11
12 from models import SourceActualite, Actualite, Discipline, Evenement, Record, ListSet, HarvestLog
13 from savoirs.globals import META
14
15 admin.site.register(Actualite)
16 admin.site.register(SourceActualite)
17 admin.site.register(Discipline)
18 admin.site.register(Evenement)
19
20 class 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
33 def title(self):
34 return self.lookup_title
35
36 FilterSpec.filter_specs.insert(0, (lambda f: f.name == 'listsets', ListSetFilterSpec))
37
38 # Ces deux classes permettent d'implémenter la possibilité d'avoir un champs readonly_fields
39 # dans l.administration.
40 # Ce champs est devenu natif à partir de la version 1.2
41 # http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields
42 from django import forms
43 class ReadOnlyWidget(forms.Widget):
44 def __init__(self, original_value, display_value):
45 self.original_value = original_value
46 self.display_value = display_value
47
48 super(ReadOnlyWidget, self).__init__()
49
50 def render(self, name, value, attrs=None):
51 if self.display_value is not None:
52 output = self.display_value
53 else:
54 output = unicode(self.original_value)
55
56 # pour les relations
57 try:
58 output = ", ".join([ls.name for ls in self.original_value.get_query_set()])
59 except:
60 pass
61
62 is_url = re.match('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', output)
63 if is_url:
64 output = "<a target='_blank' href='%s'>%s</a>" % (output, output)
65
66 return mark_safe(output)
67
68 def value_from_datadict(self, data, files, name):
69 return self.original_value
70
71 class ReadOnlyAdminFields(object):
72 def get_form(self, request, obj=None):
73 form = super(ReadOnlyAdminFields, self).get_form(request, obj)
74
75 if hasattr(self, 'readonly_fields'):
76 for field_name in self.readonly_fields:
77 if field_name in form.base_fields:
78
79 if hasattr(obj, 'get_%s_display' % field_name):
80 display_value = getattr(obj, 'get_%s_display' % field_name)()
81 else:
82 display_value = None
83
84 form.base_fields[field_name].widget = ReadOnlyWidget(getattr(obj, field_name, ''), display_value)
85 form.base_fields[field_name].required = False
86 return form
87
88
89 class RecordAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
90 fields = [
91 'server',
92 'title',
93 'creator',
94 'description',
95 'modified',
96 'identifier',
97 'uri',
98 'source',
99 'contributor',
100 'publisher',
101 'type',
102 'format',
103 'language',
104 'disciplines',
105 'thematiques',
106 'listsets',
107 'pays',
108 'regions',
109 'validated',
110 ]
111
112 search_fields = []
113 readonly_fields = []
114
115 list_filter = (
116 'validated',
117 'server',
118 'listsets',
119 'pays',
120 'regions',
121 'disciplines',
122 'thematiques',
123 )
124 list_display = (
125 #OAI et extra AUF
126 'title',
127 'subject',
128 '_description',
129 '_uri',
130 #'server',
131 'identifier',
132 #'source',
133 'modified',
134 'creator',
135 #'contributor',
136 #'language',
137 #'publisher',
138 'format',
139 'type',
140
141 #SEP 2 (aucune données récoltées)
142 #'alt_title',
143 #'abstract',
144 #'creation',
145 #'issued',
146 #'isbn',
147 #'orig_lang',
148 'validated',
149 )
150 actions = ['assigner_pays',
151 'assigner_regions',
152 'assigner_disciplines',
153 'assigner_thematiques']
154
155 # fonctions pour présenter l'information
156 def __init__(self, *args, **kwargs):
157 """Surcharge l'initialisation pour définir les champs de recherche dynamiquement,
158 et les champs en lecture seule uniquement."""
159 self.search_fields = META.keys()
160 self.readonly_fields = META.keys()
161 self.readonly_fields.append('listsets')
162 super(RecordAdmin, self).__init__(*args, **kwargs)
163
164 def _uri(self, obj):
165 """ """
166 return "<a target='_blank' href='%s'>%s</a>" % (obj.uri, obj.uri)
167 _uri.allow_tags = True
168
169 def _description(self, obj):
170 """ """
171 max = 140
172 if obj.description is not None and len(obj.description) > max:
173 return "%s..." % obj.description[:max]
174 else:
175 return obj.description
176
177 # actions
178 def assigner_pays(self, request, queryset):
179 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
180 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('pays', ",".join(selected)))
181
182 def assigner_regions(self, request, queryset):
183 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
184 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('regions', ",".join(selected)))
185
186 def assigner_thematiques(self, request, queryset):
187 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
188 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('thematiques', ",".join(selected)))
189
190 def assigner_disciplines(self, request, queryset):
191 selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
192 return HttpResponseRedirect("/admin/assigner_%s?ids=%s" % ('disciplines', ",".join(selected)))
193
194 admin.site.register(Record, RecordAdmin)
195
196 class ListSetAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
197 fields = ['spec', 'name', 'server', 'validated' ]
198 list_display = fields
199 readonly_fields = ['spec', 'name', 'server',]
200 list_filter = ('server',)
201
202 admin.site.register(ListSet, ListSetAdmin)
203
204 class HarvestLogAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
205 fields = ['context', 'name', 'added', 'updated', 'processed', 'record']
206 list_display = fields + ['date']
207 admin_order_fields = ['date']
208 search_fields = fields
209 readonly_fields = fields
210 list_filter = ('context',)
211
212 admin.site.register(HarvestLog, HarvestLogAdmin)