ajout du filtre listset dans les records si un server est selectionne
[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
6a6986bc 6from django.contrib.admin.filterspecs import RelatedFilterSpec, FilterSpec
23b5b3d5 7from django.utils.safestring import mark_safe
6a6986bc 8from django.utils.translation import ugettext as _
9from django.utils.encoding import smart_unicode, iri_to_uri
e3c3296e 10from django.http import HttpResponseRedirect
11
d972b61d 12from models import SourceActualite, Actualite, Discipline, Evenement, Record, ListSet, HarvestLog
23b5b3d5 13from savoirs.globals import META
6ef8ead4 14
92c7413b 15admin.site.register(Actualite)
79c398f6 16admin.site.register(SourceActualite)
92c7413b
CR
17admin.site.register(Discipline)
18admin.site.register(Evenement)
6ef8ead4 19
6a6986bc 20class 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
36FilterSpec.filter_specs.insert(0, (lambda f: f.name == 'listsets', ListSetFilterSpec))
37
23b5b3d5 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
42from django import forms
43class 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
d972b61d 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
23b5b3d5 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)
d972b61d 65
23b5b3d5 66 return mark_safe(output)
67
68 def value_from_datadict(self, data, files, name):
69 return self.original_value
70
71class 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
89class 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',
c65edab8 106 'listsets',
e3c3296e 107 'pays',
108 'regions',
c88d78dc 109 'validated',
23b5b3d5 110 ]
111
112 search_fields = []
113 readonly_fields = []
da9020f3 114
9692b801 115 list_filter = (
9692b801 116 'validated',
c65edab8 117 'server',
6a6986bc 118 'listsets',
9692b801 119 'pays',
120 'regions',
121 'disciplines',
122 'thematiques',
123 )
da9020f3 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',
23b5b3d5 135 #'contributor',
136 #'language',
137 #'publisher',
da9020f3 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',
c88d78dc 148 'validated',
da9020f3 149 )
e3c3296e 150 actions = ['assigner_pays',
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)
163
da9020f3 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 """ """
23b5b3d5 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
da9020f3 176
e3c3296e 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
da9020f3 194admin.site.register(Record, RecordAdmin)
195
d972b61d 196class ListSetAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
9eda5d6c 197 fields = ['spec', 'name', 'server', 'validated' ]
d972b61d 198 list_display = fields
199 readonly_fields = ['spec', 'name', 'server',]
200 list_filter = ('server',)
201
202admin.site.register(ListSet, ListSetAdmin)
203
23b5b3d5 204class HarvestLogAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
a85ba76e 205 fields = ['context', 'name', 'added', 'updated', 'processed', 'record']
23b5b3d5 206 list_display = fields + ['date']
207 admin_order_fields = ['date']
208 search_fields = fields
209 readonly_fields = fields
210 list_filter = ('context',)
211
212admin.site.register(HarvestLog, HarvestLogAdmin)