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