File: admin.py

package info (click to toggle)
python-django-ordered-model 3.7.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 592 kB
  • sloc: python: 2,139; sh: 38; makefile: 11
file content (254 lines) | stat: -rw-r--r-- 8,762 bytes parent folder | download
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
from functools import update_wrapper

from django.http import HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.encoding import escape_uri_path, iri_to_uri
from django.utils.translation import gettext_lazy as _
from django.template.loader import render_to_string
from django.contrib import admin
from django.contrib.admin.utils import unquote
from django.contrib.admin.options import csrf_protect_m
from django.contrib.admin.views.main import ChangeList
from django import VERSION


class BaseOrderedModelAdmin:
    """
    Functionality common to both OrderedModelAdmin and OrderedInlineMixin.
    """

    request_query_string = ""

    def _get_model_info(self):
        return {"app": self.model._meta.app_label, "model": self.model._meta.model_name}

    def _get_changelist(self, request):
        list_display = self.get_list_display(request)
        list_display_links = self.get_list_display_links(request, list_display)

        args = (
            request,
            self.model,
            list_display,
            list_display_links,
            self.list_filter,
            self.date_hierarchy,
            self.search_fields,
            self.list_select_related,
            self.list_per_page,
            self.list_max_show_all,
            self.list_editable,
            self,
        )

        if VERSION >= (2, 1):
            args = args + (self.sortable_by,)

        if VERSION >= (4, 0):
            args = args + (self.search_help_text,)

        return ChangeList(*args)

    @csrf_protect_m
    def changelist_view(self, request, extra_context=None):
        cl = self._get_changelist(request)
        self.request_query_string = cl.get_query_string()
        return super().changelist_view(request, extra_context)


class OrderedModelAdmin(BaseOrderedModelAdmin, admin.ModelAdmin):
    def get_urls(self):
        from django.urls import path

        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)

            wrapper.model_admin = self
            return update_wrapper(wrapper, view)

        model_info = self._get_model_info()

        return [
            path(
                "<path:object_id>/move-<direction>/",
                wrap(self.move_view),
                name="{app}_{model}_change_order".format(**model_info),
            )
        ] + super().get_urls()

    def move_view(self, request, object_id, direction):
        obj = get_object_or_404(self.model, pk=unquote(object_id))

        if direction not in ("up", "down", "top", "bottom"):
            raise Http404

        getattr(obj, direction)()

        # guts from request.get_full_path(), calculating ../../ and restoring GET arguments
        mangled = "/".join(escape_uri_path(request.path).split("/")[0:-3])
        redir_path = "%s%s%s" % (
            mangled,
            "/" if not mangled.endswith("/") else "",
            ("?" + iri_to_uri(request.META.get("QUERY_STRING", "")))
            if request.META.get("QUERY_STRING", "")
            else "",
        )

        return HttpResponseRedirect(redir_path)

    def move_up_down_links(self, obj):
        model_info = self._get_model_info()
        return render_to_string(
            "ordered_model/admin/order_controls.html",
            {
                "app_label": model_info["app"],
                "model_name": model_info["model"],
                "module_name": model_info["model"],  # for backwards compatibility
                "object_id": obj.pk,
                "urls": {
                    "up": reverse(
                        "{admin_name}:{app}_{model}_change_order".format(
                            admin_name=self.admin_site.name, **model_info
                        ),
                        args=[obj.pk, "up"],
                    ),
                    "down": reverse(
                        "{admin_name}:{app}_{model}_change_order".format(
                            admin_name=self.admin_site.name, **model_info
                        ),
                        args=[obj.pk, "down"],
                    ),
                    "top": reverse(
                        "{admin_name}:{app}_{model}_change_order".format(
                            admin_name=self.admin_site.name, **model_info
                        ),
                        args=[obj.pk, "top"],
                    ),
                    "bottom": reverse(
                        "{admin_name}:{app}_{model}_change_order".format(
                            admin_name=self.admin_site.name, **model_info
                        ),
                        args=[obj.pk, "bottom"],
                    ),
                },
                "query_string": self.request_query_string,
            },
        )

    move_up_down_links.short_description = _("Move")


class OrderedInlineModelAdminMixin:
    """
    ModelAdminMixin for classes that contain OrderedInilines
    """

    def get_urls(self):
        urls = super().get_urls()
        for inline in self.inlines:
            if issubclass(inline, OrderedInlineMixin):
                urls = inline(self.model, self.admin_site).get_urls() + urls
        return urls


class OrderedInlineMixin(BaseOrderedModelAdmin):
    def _get_model_info(self):
        return dict(
            **super()._get_model_info(),
            parent_model=self.parent_model._meta.model_name,
        )

    def get_urls(self):
        from django.urls import path

        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)

            wrapper.model_admin = self
            return update_wrapper(wrapper, view)

        model_info = self._get_model_info()
        return [
            path(
                "<path:admin_id>/{model}/<path:object_id>/move-<direction>/".format(
                    **model_info
                ),
                wrap(self.move_view),
                name="{app}_{parent_model}_{model}_change_order_inline".format(
                    **model_info
                ),
            )
        ]

    def move_view(self, request, admin_id, object_id, direction):
        obj = get_object_or_404(self.model, pk=unquote(object_id))

        if direction not in ("up", "down", "top", "bottom"):
            raise Http404

        getattr(obj, direction)()

        # guts from request.get_full_path(), calculating ../../ and restoring GET arguments
        mangled = "/".join(escape_uri_path(request.path).split("/")[0:-4] + ["change"])
        redir_path = "%s%s%s" % (
            mangled,
            "/" if not mangled.endswith("/") else "",
            ("?" + iri_to_uri(request.META.get("QUERY_STRING", "")))
            if request.META.get("QUERY_STRING", "")
            else "",
        )

        return HttpResponseRedirect(redir_path)

    def move_up_down_links(self, obj):
        if not obj.pk:
            return ""

        # Find the fields which refer to the parent model of this inline, and
        # use one of them if they aren't None.
        fields = []
        for value in obj._get_related_objects():
            # Note 'a class is considered a subclass of itself' pydocs
            if issubclass(self.parent_model, type(value)):
                if value is not None and value.pk is not None:
                    fields.append(str(value.pk))

        order_obj_name = fields[0] if len(fields) > 0 else None

        model_info = self._get_model_info()
        if not order_obj_name:
            return ""

        name = "{admin_name}:{app}_{parent_model}_{model}_change_order_inline".format(
            admin_name=self.admin_site.name, **model_info
        )

        return render_to_string(
            "ordered_model/admin/order_controls.html",
            {
                "app_label": model_info["app"],
                "model_name": model_info["model"],
                "module_name": model_info["model"],  # backwards compat
                "object_id": obj.pk,
                "urls": {
                    "up": reverse(name, args=[order_obj_name, obj.pk, "up"]),
                    "down": reverse(name, args=[order_obj_name, obj.pk, "down"]),
                    "top": reverse(name, args=[order_obj_name, obj.pk, "top"]),
                    "bottom": reverse(name, args=[order_obj_name, obj.pk, "bottom"]),
                },
                "query_string": self.request_query_string,
            },
        )

    move_up_down_links.short_description = _("Move")


class OrderedTabularInline(OrderedInlineMixin, admin.TabularInline):
    pass


class OrderedStackedInline(OrderedInlineMixin, admin.StackedInline):
    pass