retrait de actif
[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 'date_activation',
15 'user_activation',
16 'date_desactivation',
17 'user_desactivation', )
18
19 AUF_METADATA_FIELDSET_FIELDS = ('date_creation', 'user_creation',
20 'date_modification', 'user_modification',
21 'date_activation', 'user_activation',
22 'date_desactivation', 'user_desactivation',)
23
24 class AUFMetadataInlineAdminMixin(object):
25 exclude = AUF_METADATA_READONLY_FIELDS
26
27
28 class AUFMetadataAdminMixin(object):
29 """
30 Surcharge l'admin de base, pour setter automatiquement les metadata.
31 """
32 readonly_fields = AUF_METADATA_READONLY_FIELDS
33 fieldsets = (
34 ('Méta-données', {
35 'classes': ('collapse',),
36 'fields': AUF_METADATA_FIELDSET_FIELDS,
37 }),
38 )
39
40 def save_model(self, request, obj, form, change):
41 if obj.user_creation is None:
42 obj.user_creation = request.user
43 obj.date_creation = datetime.datetime.now()
44 obj.user_modification = request.user
45 obj.date_modification = datetime.datetime.now()
46 initial = getattr(form, 'initial', None)
47 if initial:
48 if form.initial['actif'] is True and obj.actif is False:
49 obj.user_desactivation = request.user
50 obj.date_desactivation = datetime.datetime.now()
51 if form.initial['actif'] is False and obj.actif is True:
52 obj.user_activation = request.user
53 obj.date_activation = datetime.datetime.now()
54 obj.save()
55
56 def has_metadata(self, instance):
57 """
58 Test si une instance de modele hérite bien de AUFMetadata.
59 """
60 test = getattr(instance, 'supprime', None)
61 return test is not None
62
63 def save_formset(self, request, form, formset, change):
64 """
65 Mettre les metadata si l'objet est créé ou modifié par inline.
66 """
67 instances = formset.save(commit=False)
68 for instance in instances:
69 if self.has_metadata(instance):
70 self.save_model(request, instance, formset.form, change)
71 else:
72 instance.save()
73 formset.save_m2m()