-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathadmin.py
282 lines (236 loc) · 11.1 KB
/
admin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""
admin
~~~~~
Admin extensions for django-reversion-compare
:copyleft: 2012-2021 by the django-reversion-compare team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
import logging
from django.conf import settings
from django.contrib import admin
from django.contrib.admin.utils import quote, unquote
from django.http import Http404
from django.shortcuts import get_object_or_404, render
from django.urls import path, reverse
from django.utils.text import capfirst
from django.utils.translation import gettext as _
from reversion import RevertError
from reversion.admin import VersionAdmin
from reversion.models import Revision, Version
from reversion_compare.compare_raw import get_version_data, pformat
from reversion_compare.forms import SelectDiffForm
from reversion_compare.helpers import html_diff
from reversion_compare.mixins import CompareMethodsMixin, CompareMixin
logger = logging.getLogger(__name__)
class BaseCompareVersionAdmin(CompareMixin, VersionAdmin):
"""
Enhanced version of VersionAdmin with a flexible compare version API.
You can define own method to compare fields in two ways (in this order):
Create a method for a field via the field name, e.g.:
"compare_%s" % field_name
Create a method for every field by his internal type
"compare_%s" % field.get_internal_type()
see: https://docs.djangoproject.com/en/1.4/howto/custom-model-fields/#django.db.models.Field.get_internal_type
If no method defined it would build a simple ndiff from repr().
example:
----------------------------------------------------------------------------
class MyModel(models.Model):
date_created = models.DateTimeField(auto_now_add=True)
last_update = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User)
content = models.TextField()
sub_text = models.ForeignKey(FooBar)
class MyModelAdmin(CompareVersionAdmin):
def compare_DateTimeField(self, obj, version1, version2, value1, value2):
''' compare all model datetime model field in ISO format '''
date1 = value1.isoformat(" ")
date2 = value2.isoformat(" ")
html = html_diff(date1, date2)
return html
def compare_sub_text(self, obj, version1, version2, value1, value2):
''' field_name example '''
return "%s -> %s" % (value1, value2)
----------------------------------------------------------------------------
"""
# Template file used for the compare view:
compare_template = "reversion-compare/compare.html"
compare_raw_template = "reversion-compare/compare_raw.html"
# change template from django-reversion to add compare selection form:
object_history_template = "reversion-compare/object_history.html"
def get_urls(self):
"""Returns the additional urls used by the Reversion admin."""
urls = super().get_urls()
admin_site = self.admin_site
opts = self.model._meta
info = opts.app_label, opts.model_name
reversion_urls = [
path(
"<str:object_id>/history/compare/",
admin_site.admin_view(self.compare_view),
name="%s_%s_compare" % info
)
]
return reversion_urls + urls
def _get_action_list(self, request, object_id, extra_context=None):
"""Renders the history view."""
object_id = unquote(object_id) # Underscores in primary key get quoted to "_5F"
opts = self.model._meta
action_list = [
{
"version": version,
"revision": version.revision,
"url": reverse(
f"{self.admin_site.name}:{opts.app_label}_{opts.model_name}_revision",
args=(quote(version.object_id), version.id),
),
}
for version in self._order_version_queryset(
Version.objects.get_for_object_reference(self.model, object_id).select_related("revision__user")
)
]
return action_list
def history_view(self, request, object_id, extra_context=None):
"""Renders the history view."""
action_list = self._get_action_list(request, object_id, extra_context=extra_context)
if len(action_list) < 2:
# Less than two history items aren't enough to compare ;)
comparable = False
else:
comparable = True
# for pre selecting the compare radio buttons depend on the ordering:
if self.history_latest_first:
action_list[0]["first"] = True
action_list[1]["second"] = True
else:
action_list[-1]["first"] = True
action_list[-2]["second"] = True
# Compile the context.
context = {"action_list": action_list, "comparable": comparable, "compare_view": True}
context.update(extra_context or {})
return super().history_view(request, object_id, context)
def compare_view(self, request, object_id, extra_context=None):
"""
compare two versions.
Used self.make_compare() to create the html diff.
"""
if self.compare is None:
raise Http404("Compare view not enabled.")
form = SelectDiffForm(request.GET)
if not form.is_valid():
msg = "Wrong version IDs."
if settings.DEBUG:
msg += f" (form errors: {', '.join(form.errors)})"
raise Http404(msg)
version_id1 = form.cleaned_data["version_id1"]
version_id2 = form.cleaned_data["version_id2"]
if version_id1 > version_id2:
# Compare always the newest one (#2) with the older one (#1)
version_id1, version_id2 = version_id2, version_id1
object_id = unquote(object_id) # Underscores in primary key get quoted to "_5F"
obj = get_object_or_404(self.model, pk=object_id)
queryset = Version.objects.get_for_object(obj)
version1 = get_object_or_404(queryset, pk=version_id1)
version2 = get_object_or_404(queryset, pk=version_id2)
next_version = queryset.filter(pk__gt=version_id2).last()
prev_version = queryset.filter(pk__lt=version_id1).first()
try:
compare_data, has_unfollowed_fields = self.compare(obj, version1, version2)
except RevertError as err:
logger.exception('Fallback compare caused by: %s', err)
# A old version can't be loaded.
# e.g.: model was migrated and version JSON data not, see:
# https://github.com/etianen/django-reversion/issues/859
# Fallback to JSON compare
return self.compare_raw(request, obj, version1, version2, compare_error=err, extra_context=extra_context)
opts = self.model._meta
context = {
**self.admin_site.each_context(request),
"opts": opts,
"app_label": opts.app_label,
"model_name": capfirst(opts.verbose_name),
"title": _("Compare %(name)s") % {"name": version1.object_repr},
"obj": obj,
"compare_data": compare_data,
"has_unfollowed_fields": has_unfollowed_fields,
"version1": version1,
"version2": version2,
"changelist_url": reverse(f"{self.admin_site.name}:{opts.app_label}_{opts.model_name}_changelist"),
"original": obj,
"history_url": reverse(
f"{self.admin_site.name}:{opts.app_label}_{opts.model_name}_history", args=(quote(obj.pk),)
),
"save_url": reverse(
f"{self.admin_site.name}:{opts.app_label}_{opts.model_name}_revision",
args=(quote(version1.object_id), version1.id),
),
}
# don't use urlencode with dict for generate prev/next-urls
# Otherwise we can't unitests it!
if next_version:
next_url = f"?version_id1={version2.id:d}&version_id2={next_version.id:d}"
context.update({"next_url": next_url})
if prev_version:
prev_url = f"?version_id1={prev_version.id:d}&version_id2={version1.id:d}"
context.update({"prev_url": prev_url})
context.update(extra_context or {})
return render(request, self.compare_template or self._get_template_list("compare.html"), context)
def compare_raw(self, request, obj, version1, version2, compare_error, extra_context=None):
"""
Fallback: compare the raw json data.
"""
version1data = get_version_data(version1)
version2data = get_version_data(version2)
version1pformat = pformat(version1data)
version2pformat = pformat(version2data)
# TODO: Generate a nicer diff ;)
diff_html = html_diff(version1pformat, version2pformat)
opts = self.model._meta
context = {
**self.admin_site.each_context(request),
"opts": opts,
"app_label": opts.app_label,
"model_name": capfirst(opts.verbose_name),
"title": _("Compare %(name)s") % {"name": version1.object_repr},
"obj": obj,
"compare_error": compare_error,
"diff_html": diff_html,
"version1": version1,
"version2": version2,
"changelist_url": reverse(f"{self.admin_site.name}:{opts.app_label}_{opts.model_name}_changelist"),
"original": obj,
"history_url": reverse(
f"{self.admin_site.name}:{opts.app_label}_{opts.model_name}_history", args=(quote(obj.pk),)
),
"save_url": reverse(
f"{self.admin_site.name}:{opts.app_label}_{opts.model_name}_revision",
args=(quote(version1.object_id), version1.id),
),
}
context.update(extra_context or {})
return render(request, self.compare_raw_template or self._get_template_list("compare_raw.html"), context)
class CompareVersionAdmin(CompareMethodsMixin, BaseCompareVersionAdmin):
"""
expand the base class with prepared compare methods. This is the
class to inherit
"""
if hasattr(settings, "ADD_REVERSION_ADMIN") and settings.ADD_REVERSION_ADMIN:
@admin.register(Revision)
class RevisionAdmin(admin.ModelAdmin):
list_display = ("id", "date_created", "user", "comment")
list_display_links = ("date_created",)
list_select_related = ("user",)
date_hierarchy = "date_created"
ordering = ("-date_created",)
list_filter = ("user", "comment")
search_fields = ("user", "comment")
raw_id_fields = ("user",)
@admin.register(Version)
class VersionAdmin(admin.ModelAdmin):
def comment(self, obj):
return obj.revision.comment
list_display = ("object_repr", "comment", "object_id", "content_type", "format")
list_display_links = ("object_repr", "object_id")
list_filter = ("content_type", "format")
list_select_related = ("revision", "content_type")
search_fields = ("object_repr", "serialized_data")
raw_id_fields = ("revision", "content_type")