bae1d3dff0e7d2076d0451af88c04dc4b0d23038
[auf_rh_dae.git] / src / auf.django.metadata / auf / django / metadata / admin.py
1 # -*- encoding: utf-8 -*-
2
3 import datetime
4 from django.contrib import admin
5 from django.contrib import messages
6 from django.shortcuts import redirect
7 from models import AUFMetadata
8
9 AUF_METADATA_READONLY_FIELDS = ('supprime',
10 'date_creation',
11 'user_creation',
12 'date_modification',
13 'user_modification',
14 )
15
16 AUF_METADATA_FIELDSET_FIELDS = ('date_creation', 'user_creation',
17 'date_modification', 'user_modification',
18 )
19
20 class AUFMetadataInlineAdminMixin(object):
21 exclude = AUF_METADATA_READONLY_FIELDS
22
23
24 class AUFMetadataAdminMixin(object):
25 """
26 Surcharge l'admin de base, pour setter automatiquement les metadata.
27 """
28 readonly_fields = AUF_METADATA_READONLY_FIELDS
29 fieldsets = (
30 ('Méta-données', {
31 'classes': ('collapse',),
32 'fields': AUF_METADATA_FIELDSET_FIELDS,
33 }),
34 )
35
36 def save_model(self, request, obj, form, change):
37 if obj.user_creation is None:
38 obj.user_creation = request.user
39 obj.date_creation = datetime.datetime.now()
40 obj.user_modification = request.user
41 obj.date_modification = datetime.datetime.now()
42 obj.save()
43
44 def has_metadata(self, instance):
45 """
46 Test si une instance de modele hérite bien de AUFMetadata.
47 """
48 test = getattr(instance, 'supprime', None)
49 return test is not None
50
51 def save_formset(self, request, form, formset, change):
52 """
53 Mettre les metadata si l'objet est créé ou modifié par inline.
54 """
55 instances = formset.save(commit=False)
56 for instance in instances:
57 if self.has_metadata(instance):
58 self.save_model(request, instance, formset.form, change)
59 else:
60 instance.save()
61 formset.save_m2m()