ferme #460 ajout du dashboard pour connaitre les references à traiter
[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
CR
19admin.site.register(Discipline)
20admin.site.register(Evenement)
6ef8ead4 21
6a6986bc 22class 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
6a6986bc 35FilterSpec.filter_specs.insert(0, (lambda f: f.name == 'listsets', ListSetFilterSpec))
36
23b5b3d5 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
41from django import forms
42class 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
d972b61d 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
23b5b3d5 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)
d972b61d 64
23b5b3d5 65 return mark_safe(output)
66
67 def value_from_datadict(self, data, files, name):
68 return self.original_value
69
70class 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
88class 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',
e3c3296e 105 'pays',
106 'regions',
c88d78dc 107 'validated',
23b5b3d5 108 ]
109
110 search_fields = []
111 readonly_fields = []
da9020f3 112
9692b801 113 list_filter = (
9692b801 114 'validated',
c65edab8 115 'server',
6a6986bc 116 'listsets',
9692b801 117 'pays',
118 'regions',
119 'disciplines',
120 'thematiques',
121 )
da9020f3 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',
23b5b3d5 133 #'contributor',
134 #'language',
135 #'publisher',
da9020f3 136 'format',
137 'type',
138
6d885e0c 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',
da9020f3 148 )
e3c3296e 149 actions = ['assigner_pays',
150 'assigner_regions',
151 'assigner_disciplines',
152 'assigner_thematiques']
da9020f3 153
e3c3296e 154 # fonctions pour présenter l'information
23b5b3d5 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()
d972b61d 160 self.readonly_fields.append('listsets')
23b5b3d5 161 super(RecordAdmin, self).__init__(*args, **kwargs)
6d885e0c 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
23b5b3d5 168
da9020f3 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 """ """
23b5b3d5 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
da9020f3 181
e3c3296e 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
da9020f3 199admin.site.register(Record, RecordAdmin)
200
d972b61d 201class ListSetAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
9eda5d6c 202 fields = ['spec', 'name', 'server', 'validated' ]
d972b61d 203 list_display = fields
204 readonly_fields = ['spec', 'name', 'server',]
205 list_filter = ('server',)
206
207admin.site.register(ListSet, ListSetAdmin)
208
23b5b3d5 209class HarvestLogAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
a85ba76e 210 fields = ['context', 'name', 'added', 'updated', 'processed', 'record']
23b5b3d5 211 list_display = fields + ['date']
212 admin_order_fields = ['date']
213 search_fields = fields
214 readonly_fields = fields
215 list_filter = ('context',)
216
217admin.site.register(HarvestLog, HarvestLogAdmin)
6d885e0c 218
219class ProfileInline(admin.TabularInline):
220 model = Profile
221 fk_name = 'user'
222 max_num = 1
223
224class UserProfileAdmin(UserAdmin):
225 inlines = [ProfileInline, ]
226
227admin.site.unregister(User)
228admin.site.register(User, UserProfileAdmin)
229