django-content-studio 1.0.0b5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- content_studio/__init__.py +7 -0
- content_studio/admin.py +307 -0
- content_studio/apps.py +100 -0
- content_studio/dashboard/__init__.py +64 -0
- content_studio/dashboard/activity_log.py +35 -0
- content_studio/filters.py +124 -0
- content_studio/form.py +178 -0
- content_studio/formats.py +59 -0
- content_studio/login_backends/__init__.py +21 -0
- content_studio/login_backends/username_password.py +82 -0
- content_studio/media_library/serializers.py +25 -0
- content_studio/media_library/viewsets.py +132 -0
- content_studio/models.py +73 -0
- content_studio/paginators.py +20 -0
- content_studio/router.py +14 -0
- content_studio/serializers.py +118 -0
- content_studio/settings.py +152 -0
- content_studio/static/content_studio/assets/browser-ponyfill-Ct7s-5jI.js +2 -0
- content_studio/static/content_studio/assets/browser-ponyfill-TyWUZ1Oq.js +2 -0
- content_studio/static/content_studio/assets/index.css +1 -0
- content_studio/static/content_studio/assets/index.js +249 -0
- content_studio/static/content_studio/assets/inter-cyrillic-ext-wght-normal.woff2 +0 -0
- content_studio/static/content_studio/assets/inter-cyrillic-wght-normal.woff2 +0 -0
- content_studio/static/content_studio/assets/inter-greek-ext-wght-normal.woff2 +0 -0
- content_studio/static/content_studio/assets/inter-greek-wght-normal.woff2 +0 -0
- content_studio/static/content_studio/assets/inter-latin-ext-wght-normal.woff2 +0 -0
- content_studio/static/content_studio/assets/inter-latin-wght-normal.woff2 +0 -0
- content_studio/static/content_studio/assets/inter-vietnamese-wght-normal.woff2 +0 -0
- content_studio/static/content_studio/icons/pi/Phosphor-Bold.svg +3057 -0
- content_studio/static/content_studio/icons/pi/Phosphor-Bold.ttf +0 -0
- content_studio/static/content_studio/icons/pi/Phosphor-Bold.woff +0 -0
- content_studio/static/content_studio/icons/pi/Phosphor-Bold.woff2 +0 -0
- content_studio/static/content_studio/icons/pi/style.css +4627 -0
- content_studio/static/content_studio/img/media_placeholder.svg +1 -0
- content_studio/static/content_studio/locales/en/translation.json +85 -0
- content_studio/static/content_studio/locales/nl/translation.json +90 -0
- content_studio/static/content_studio/vite.svg +1 -0
- content_studio/templates/content_studio/index.html +24 -0
- content_studio/token_backends/__init__.py +39 -0
- content_studio/token_backends/jwt.py +56 -0
- content_studio/urls.py +21 -0
- content_studio/utils.py +62 -0
- content_studio/views.py +181 -0
- content_studio/viewsets.py +114 -0
- content_studio/widgets.py +83 -0
- django_content_studio-1.0.0b5.dist-info/LICENSE +21 -0
- django_content_studio-1.0.0b5.dist-info/METADATA +86 -0
- django_content_studio-1.0.0b5.dist-info/RECORD +49 -0
- django_content_studio-1.0.0b5.dist-info/WHEEL +4 -0
content_studio/admin.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
from typing import Type
|
|
3
|
+
|
|
4
|
+
from django.contrib import admin
|
|
5
|
+
from django.db import models
|
|
6
|
+
from django.db.models import Model
|
|
7
|
+
from rest_framework.request import HttpRequest
|
|
8
|
+
|
|
9
|
+
from . import widgets, formats
|
|
10
|
+
from .form import FormSet, FormSetGroup, Field, Component
|
|
11
|
+
from .login_backends import LoginBackendManager
|
|
12
|
+
from .token_backends import TokenBackendManager
|
|
13
|
+
from .utils import get_related_field_name, flatten
|
|
14
|
+
|
|
15
|
+
register = admin.register
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class StackedInline(admin.StackedInline):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TabularInline(admin.TabularInline):
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class AdminSite(admin.AdminSite):
|
|
27
|
+
"""
|
|
28
|
+
Enhanced admin site for Django Content Studio.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
token_backend = TokenBackendManager()
|
|
32
|
+
|
|
33
|
+
login_backend = LoginBackendManager()
|
|
34
|
+
|
|
35
|
+
dashboard = None
|
|
36
|
+
|
|
37
|
+
model_groups = None
|
|
38
|
+
|
|
39
|
+
default_widget_mapping = {
|
|
40
|
+
models.CharField: widgets.InputWidget,
|
|
41
|
+
models.IntegerField: widgets.InputWidget,
|
|
42
|
+
models.SmallIntegerField: widgets.InputWidget,
|
|
43
|
+
models.BigIntegerField: widgets.InputWidget,
|
|
44
|
+
models.PositiveIntegerField: widgets.InputWidget,
|
|
45
|
+
models.PositiveSmallIntegerField: widgets.InputWidget,
|
|
46
|
+
models.PositiveBigIntegerField: widgets.InputWidget,
|
|
47
|
+
models.FloatField: widgets.InputWidget,
|
|
48
|
+
models.DecimalField: widgets.InputWidget,
|
|
49
|
+
models.SlugField: widgets.SlugWidget,
|
|
50
|
+
models.TextField: widgets.TextAreaWidget,
|
|
51
|
+
models.BooleanField: widgets.CheckboxWidget,
|
|
52
|
+
models.NullBooleanField: widgets.CheckboxWidget,
|
|
53
|
+
models.ForeignKey: widgets.ForeignKeyWidget,
|
|
54
|
+
models.ManyToManyField: widgets.ManyToManyWidget,
|
|
55
|
+
models.OneToOneField: widgets.ForeignKeyWidget,
|
|
56
|
+
models.DateField: widgets.DateWidget,
|
|
57
|
+
models.DateTimeField: widgets.DateTimeWidget,
|
|
58
|
+
models.TimeField: widgets.TimeWidget,
|
|
59
|
+
models.JSONField: widgets.JSONWidget,
|
|
60
|
+
# Common third-party fields
|
|
61
|
+
"AutoSlugField": widgets.SlugWidget,
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
default_format_mapping = {
|
|
65
|
+
models.CharField: formats.TextFormat,
|
|
66
|
+
models.IntegerField: formats.NumberFormat,
|
|
67
|
+
models.SmallIntegerField: formats.NumberFormat,
|
|
68
|
+
models.BigIntegerField: formats.NumberFormat,
|
|
69
|
+
models.PositiveIntegerField: formats.NumberFormat,
|
|
70
|
+
models.PositiveSmallIntegerField: formats.NumberFormat,
|
|
71
|
+
models.PositiveBigIntegerField: formats.NumberFormat,
|
|
72
|
+
models.FloatField: formats.NumberFormat,
|
|
73
|
+
models.DecimalField: formats.NumberFormat,
|
|
74
|
+
models.SlugField: formats.TextFormat,
|
|
75
|
+
models.TextField: formats.TextFormat,
|
|
76
|
+
models.BooleanField: formats.BooleanFormat,
|
|
77
|
+
models.NullBooleanField: formats.BooleanFormat,
|
|
78
|
+
models.DateField: formats.DateFormat,
|
|
79
|
+
models.DateTimeField: formats.DateTimeFormat,
|
|
80
|
+
models.TimeField: formats.TimeFormat,
|
|
81
|
+
models.ForeignKey: formats.ForeignKeyFormat,
|
|
82
|
+
models.OneToOneField: formats.ForeignKeyFormat,
|
|
83
|
+
models.JSONField: formats.JSONFormat,
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
def setup(self):
|
|
87
|
+
# Add token backend's view set to the
|
|
88
|
+
# Content Studio router.
|
|
89
|
+
self.token_backend.set_up_router()
|
|
90
|
+
# Add login backend's view set to the
|
|
91
|
+
# Content Studio router.
|
|
92
|
+
self.login_backend.set_up_router()
|
|
93
|
+
# Add dashboard's view set to the
|
|
94
|
+
# Content Studio router.
|
|
95
|
+
if self.dashboard:
|
|
96
|
+
self.dashboard.set_up_router()
|
|
97
|
+
|
|
98
|
+
def get_thumbnail(self, obj) -> str:
|
|
99
|
+
"""
|
|
100
|
+
Method for getting and manipulating the image path (or URL).
|
|
101
|
+
By default, this returns the image path as is.
|
|
102
|
+
"""
|
|
103
|
+
return obj.file.url
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
admin_site = AdminSite()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class ModelAdmin(admin.ModelAdmin):
|
|
110
|
+
"""
|
|
111
|
+
Enhanced model admin for Django Content Studio and integration with
|
|
112
|
+
Django Content Framework. Although it's relatively backwards compatible,
|
|
113
|
+
some default behavior has been changed.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
# Whether the model is a singleton and should not show
|
|
117
|
+
# the list view.
|
|
118
|
+
is_singleton = False
|
|
119
|
+
|
|
120
|
+
# Override the widget used for certain fields by adding
|
|
121
|
+
# a map of field to widget. Fields that are not included
|
|
122
|
+
# will fall back to their default widget.
|
|
123
|
+
#
|
|
124
|
+
# @example
|
|
125
|
+
# widget_mapping = {'is_published': widgets.SwitchWidget}
|
|
126
|
+
widget_mapping = None
|
|
127
|
+
|
|
128
|
+
# Override the format used for certain fields by adding
|
|
129
|
+
# a map of field to format. Fields that are not included
|
|
130
|
+
# will fall back to their default format.
|
|
131
|
+
#
|
|
132
|
+
# @example
|
|
133
|
+
# format_mapping = {'file_size': widgets.FileSizeWidget}
|
|
134
|
+
format_mapping = None
|
|
135
|
+
|
|
136
|
+
# We set a lower limit than Django's default of 100
|
|
137
|
+
list_per_page = 20
|
|
138
|
+
|
|
139
|
+
# Description shown below model name on list pages
|
|
140
|
+
list_description = ""
|
|
141
|
+
|
|
142
|
+
# Configure the main section in the edit-view.
|
|
143
|
+
edit_main: list[type[FormSetGroup | FormSet | Field | str]] = []
|
|
144
|
+
|
|
145
|
+
# Configure the sidebar in the edit-view.
|
|
146
|
+
edit_sidebar: list[type[FormSet | Field | str]] = []
|
|
147
|
+
|
|
148
|
+
icon = None
|
|
149
|
+
|
|
150
|
+
def has_add_permission(self, request):
|
|
151
|
+
is_singleton = getattr(self.model, "is_singleton", False)
|
|
152
|
+
|
|
153
|
+
# Don't allow to add more than one singleton object.
|
|
154
|
+
if is_singleton and self.model.objects.get():
|
|
155
|
+
return False
|
|
156
|
+
|
|
157
|
+
return super().has_add_permission(request)
|
|
158
|
+
|
|
159
|
+
def has_delete_permission(self, request, obj=None):
|
|
160
|
+
is_singleton = getattr(self.model, "is_singleton", False)
|
|
161
|
+
|
|
162
|
+
if is_singleton:
|
|
163
|
+
return False
|
|
164
|
+
|
|
165
|
+
return super().has_delete_permission(request, obj)
|
|
166
|
+
|
|
167
|
+
def get_component(self, component_id: uuid.UUID):
|
|
168
|
+
"""
|
|
169
|
+
Retrieves a component from the edit_main or edit_sidebar attributes by ID.
|
|
170
|
+
:param component_id:
|
|
171
|
+
:return:
|
|
172
|
+
"""
|
|
173
|
+
all_fields = getattr(self, "edit_main", []) + getattr(self, "edit_sidebar", [])
|
|
174
|
+
|
|
175
|
+
flat_fields = flatten(
|
|
176
|
+
[f.get_fields() if hasattr(f, "get_fields") else [f] for f in all_fields]
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
components = [c for c in flat_fields if issubclass(c.__class__, Component)]
|
|
180
|
+
|
|
181
|
+
for component in components:
|
|
182
|
+
if component.component_id == component_id:
|
|
183
|
+
return component
|
|
184
|
+
|
|
185
|
+
return None
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class AdminSerializer:
|
|
189
|
+
"""
|
|
190
|
+
Class for serializing Django admin classes.
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
def __init__(self, admin_class: ModelAdmin):
|
|
194
|
+
self.admin_class = admin_class
|
|
195
|
+
|
|
196
|
+
def serialize(self, request: HttpRequest):
|
|
197
|
+
admin_class = self.admin_class
|
|
198
|
+
format_mapping = getattr(admin_class, "format_mapping", None) or {}
|
|
199
|
+
widget_mapping = getattr(admin_class, "widget_mapping", None) or {}
|
|
200
|
+
|
|
201
|
+
return {
|
|
202
|
+
"icon": getattr(admin_class, "icon", None),
|
|
203
|
+
"is_singleton": getattr(admin_class, "is_singleton", False),
|
|
204
|
+
"edit": {
|
|
205
|
+
"main": self.serialize_edit_main(request),
|
|
206
|
+
"sidebar": self.serialize_edit_sidebar(request),
|
|
207
|
+
"inlines": [
|
|
208
|
+
{
|
|
209
|
+
"model": inline.model._meta.label_lower,
|
|
210
|
+
"fk_name": get_related_field_name(inline, admin_class.model),
|
|
211
|
+
"list_display": getattr(inline, "list_display", None)
|
|
212
|
+
or ["__str__"],
|
|
213
|
+
}
|
|
214
|
+
for inline in admin_class.inlines
|
|
215
|
+
],
|
|
216
|
+
},
|
|
217
|
+
"list": {
|
|
218
|
+
"per_page": admin_class.list_per_page,
|
|
219
|
+
"description": getattr(admin_class, "list_description", ""),
|
|
220
|
+
"display": admin_class.list_display,
|
|
221
|
+
"search": len(admin_class.search_fields) > 0,
|
|
222
|
+
"filter": admin_class.list_filter,
|
|
223
|
+
"sortable_by": admin_class.sortable_by,
|
|
224
|
+
},
|
|
225
|
+
"widget_mapping": {
|
|
226
|
+
field: widget.serialize() for field, widget in widget_mapping.items()
|
|
227
|
+
},
|
|
228
|
+
"format_mapping": {
|
|
229
|
+
field: format.serialize() for field, format in format_mapping.items()
|
|
230
|
+
},
|
|
231
|
+
"permissions": {
|
|
232
|
+
"add_permission": admin_class.has_add_permission(request),
|
|
233
|
+
"delete_permission": admin_class.has_delete_permission(request),
|
|
234
|
+
"change_permission": admin_class.has_change_permission(request),
|
|
235
|
+
"view_permission": admin_class.has_view_permission(request),
|
|
236
|
+
},
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
def serialize_edit_main(self, request):
|
|
240
|
+
admin_class = self.admin_class
|
|
241
|
+
|
|
242
|
+
return [
|
|
243
|
+
i.serialize()
|
|
244
|
+
for i in self.get_edit_main(
|
|
245
|
+
getattr(admin_class, "edit_main", admin_class.get_fields(request))
|
|
246
|
+
)
|
|
247
|
+
]
|
|
248
|
+
|
|
249
|
+
def serialize_edit_sidebar(self, request):
|
|
250
|
+
admin_class = self.admin_class
|
|
251
|
+
|
|
252
|
+
return [
|
|
253
|
+
i.serialize()
|
|
254
|
+
for i in self.get_edit_sidebar(getattr(admin_class, "edit_sidebar", None))
|
|
255
|
+
]
|
|
256
|
+
|
|
257
|
+
def get_edit_main(self, edit_main):
|
|
258
|
+
"""
|
|
259
|
+
Returns a normalized list of form set groups.
|
|
260
|
+
|
|
261
|
+
Form sets will be wrapped in a form set group. If the edit_main attribute is a list of fields,
|
|
262
|
+
they are wrapped in a form set and a form set group.
|
|
263
|
+
"""
|
|
264
|
+
if not edit_main:
|
|
265
|
+
return []
|
|
266
|
+
if isinstance(edit_main[0], FormSetGroup):
|
|
267
|
+
return edit_main
|
|
268
|
+
if isinstance(edit_main[0], FormSet):
|
|
269
|
+
return [FormSetGroup(formsets=edit_main)]
|
|
270
|
+
|
|
271
|
+
return [FormSetGroup(formsets=[FormSet(fields=edit_main)])]
|
|
272
|
+
|
|
273
|
+
def get_edit_sidebar(self, edit_sidebar):
|
|
274
|
+
"""
|
|
275
|
+
Returns a normalized list of form sets for the edit_sidebar.
|
|
276
|
+
|
|
277
|
+
If the edit_sidebar attribute is a list of fields,
|
|
278
|
+
they are wrapped in a form set.
|
|
279
|
+
"""
|
|
280
|
+
if not edit_sidebar:
|
|
281
|
+
return []
|
|
282
|
+
if isinstance(edit_sidebar[0], FormSet):
|
|
283
|
+
return edit_sidebar
|
|
284
|
+
|
|
285
|
+
return [FormSet(fields=edit_sidebar)]
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class ModelGroup:
|
|
289
|
+
name = None
|
|
290
|
+
label = None
|
|
291
|
+
icon = None
|
|
292
|
+
color = None
|
|
293
|
+
models = None
|
|
294
|
+
|
|
295
|
+
def __init__(
|
|
296
|
+
self,
|
|
297
|
+
name: str,
|
|
298
|
+
label: str = None,
|
|
299
|
+
icon: str = None,
|
|
300
|
+
color: str = None,
|
|
301
|
+
models: list[Type[Model]] = None,
|
|
302
|
+
):
|
|
303
|
+
self.name = name
|
|
304
|
+
self.label = label or name.capitalize()
|
|
305
|
+
self.icon = icon
|
|
306
|
+
self.color = color
|
|
307
|
+
self.models = models or []
|
content_studio/apps.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
from django.apps import AppConfig
|
|
2
|
+
from django.contrib import admin
|
|
3
|
+
|
|
4
|
+
from . import VERSION
|
|
5
|
+
from .paginators import ContentPagination
|
|
6
|
+
from .settings import cs_settings
|
|
7
|
+
from .utils import is_runserver
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class DjangoContentStudioConfig(AppConfig):
|
|
11
|
+
name = "content_studio"
|
|
12
|
+
label = "content_studio"
|
|
13
|
+
initialized = False
|
|
14
|
+
|
|
15
|
+
def ready(self):
|
|
16
|
+
from .utils import log
|
|
17
|
+
|
|
18
|
+
if is_runserver() and not self.initialized:
|
|
19
|
+
self.initialized = True
|
|
20
|
+
|
|
21
|
+
log("\n")
|
|
22
|
+
log("----------------------------------------")
|
|
23
|
+
log("Django Content Studio")
|
|
24
|
+
log(f"Version {VERSION}")
|
|
25
|
+
log("----------------------------------------")
|
|
26
|
+
log(":rocket:", "Starting Django Content Studio")
|
|
27
|
+
log(":mag:", "Discovering admin models...")
|
|
28
|
+
registered_models = len(admin.site._registry)
|
|
29
|
+
log(
|
|
30
|
+
":white_check_mark:",
|
|
31
|
+
f"[green]Found {registered_models} admin models[/green]",
|
|
32
|
+
)
|
|
33
|
+
# Set up admin site routes
|
|
34
|
+
admin_site = cs_settings.ADMIN_SITE
|
|
35
|
+
admin_site.setup()
|
|
36
|
+
|
|
37
|
+
# Set up content CRUD APIs
|
|
38
|
+
self._create_crud_api()
|
|
39
|
+
|
|
40
|
+
log("\n")
|
|
41
|
+
|
|
42
|
+
def _create_crud_api(self):
|
|
43
|
+
from .utils import log
|
|
44
|
+
|
|
45
|
+
for model, admin_model in admin.site._registry.items():
|
|
46
|
+
self._create_view_set(model, admin_model)
|
|
47
|
+
|
|
48
|
+
for inline in admin_model.inlines:
|
|
49
|
+
self._create_view_set(
|
|
50
|
+
parent=model, model=inline.model, admin_model=inline
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
log(
|
|
54
|
+
":white_check_mark:",
|
|
55
|
+
f"[green]Created CRUD API[/green]",
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
def _create_view_set(self, model, admin_model, parent=None):
|
|
59
|
+
from .viewsets import BaseModelViewSet
|
|
60
|
+
from .router import content_studio_router
|
|
61
|
+
from .serializers import ContentSerializer
|
|
62
|
+
|
|
63
|
+
class Pagination(ContentPagination):
|
|
64
|
+
page_size = getattr(admin_model, "list_per_page", 10)
|
|
65
|
+
|
|
66
|
+
class ViewSet(BaseModelViewSet):
|
|
67
|
+
_model = model
|
|
68
|
+
_admin_model = admin_model
|
|
69
|
+
is_singleton = getattr(admin_model, "is_singleton", False)
|
|
70
|
+
pagination_class = Pagination
|
|
71
|
+
queryset = _model.objects.all()
|
|
72
|
+
search_fields = list(getattr(_admin_model, "search_fields", []))
|
|
73
|
+
|
|
74
|
+
def get_serializer_class(self):
|
|
75
|
+
# For list views we include the specified list_display fields.
|
|
76
|
+
if self.action == "list" and not self.is_singleton:
|
|
77
|
+
available_fields = [
|
|
78
|
+
"id",
|
|
79
|
+
"__str__",
|
|
80
|
+
] + list(getattr(self._admin_model, "list_display", []))
|
|
81
|
+
# In all other cases we include all fields.
|
|
82
|
+
else:
|
|
83
|
+
available_fields = "__all__"
|
|
84
|
+
|
|
85
|
+
class Serializer(ContentSerializer):
|
|
86
|
+
|
|
87
|
+
class Meta:
|
|
88
|
+
model = self._model
|
|
89
|
+
fields = available_fields
|
|
90
|
+
|
|
91
|
+
return Serializer
|
|
92
|
+
|
|
93
|
+
if parent:
|
|
94
|
+
prefix = f"api/inlines/{parent._meta.label_lower}/{model._meta.label_lower}"
|
|
95
|
+
basename = f"content_studio_api-{parent._meta.label_lower}-{model._meta.label_lower}"
|
|
96
|
+
else:
|
|
97
|
+
prefix = f"api/content/{model._meta.label_lower}"
|
|
98
|
+
basename = f"content_studio_api-{model._meta.label_lower}"
|
|
99
|
+
|
|
100
|
+
content_studio_router.register(prefix, ViewSet, basename)
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
from rest_framework.decorators import action
|
|
2
|
+
from rest_framework.exceptions import NotFound
|
|
3
|
+
from rest_framework.parsers import JSONParser
|
|
4
|
+
from rest_framework.renderers import JSONRenderer
|
|
5
|
+
from rest_framework.response import Response
|
|
6
|
+
from rest_framework.viewsets import ViewSet
|
|
7
|
+
|
|
8
|
+
from content_studio.settings import cs_settings
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Dashboard:
|
|
12
|
+
"""
|
|
13
|
+
The Dashboard class is used to define the structure of the dashboard
|
|
14
|
+
in Django Content Studio.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
widgets = None
|
|
18
|
+
|
|
19
|
+
def __init__(self, **kwargs):
|
|
20
|
+
self.widgets = kwargs.get("widgets", [])
|
|
21
|
+
|
|
22
|
+
def set_up_router(self):
|
|
23
|
+
from content_studio.router import content_studio_router
|
|
24
|
+
|
|
25
|
+
content_studio_router.register(
|
|
26
|
+
"api/dashboard",
|
|
27
|
+
DashboardViewSet,
|
|
28
|
+
basename="content_studio_dashboard",
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
def serialize(self):
|
|
32
|
+
return {
|
|
33
|
+
"widgets": [
|
|
34
|
+
{"name": w.__class__.__name__, "col_span": getattr(w, "col_span", 1)}
|
|
35
|
+
for w in self.widgets
|
|
36
|
+
]
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class DashboardViewSet(ViewSet):
|
|
41
|
+
parser_classes = [JSONParser]
|
|
42
|
+
renderer_classes = [JSONRenderer]
|
|
43
|
+
|
|
44
|
+
def __init__(self, *args, **kwargs):
|
|
45
|
+
super(ViewSet, self).__init__()
|
|
46
|
+
admin_site = cs_settings.ADMIN_SITE
|
|
47
|
+
|
|
48
|
+
self.dashboard = admin_site.dashboard
|
|
49
|
+
self.authentication_classes = [
|
|
50
|
+
admin_site.token_backend.active_backend.authentication_class
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
@action(detail=False, url_path="(?P<name>[^/.]+)")
|
|
54
|
+
def get(self, request, name=None):
|
|
55
|
+
widget = None
|
|
56
|
+
|
|
57
|
+
for w in self.dashboard.widgets:
|
|
58
|
+
if name == w.__class__.__name__.lower():
|
|
59
|
+
widget = w
|
|
60
|
+
|
|
61
|
+
if not widget:
|
|
62
|
+
raise NotFound()
|
|
63
|
+
|
|
64
|
+
return Response(data=widget.get_data(request))
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from content_studio.serializers import ContentSerializer
|
|
2
|
+
from django.contrib.admin.models import LogEntry
|
|
3
|
+
from rest_framework import serializers
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class LogEntrySerializer(ContentSerializer):
|
|
7
|
+
object_model = serializers.SerializerMethodField()
|
|
8
|
+
|
|
9
|
+
class Meta:
|
|
10
|
+
model = LogEntry
|
|
11
|
+
fields = [
|
|
12
|
+
"id",
|
|
13
|
+
"action_flag",
|
|
14
|
+
"action_time",
|
|
15
|
+
"user",
|
|
16
|
+
"object_id",
|
|
17
|
+
"object_repr",
|
|
18
|
+
"object_model",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
def get_object_model(self, obj):
|
|
22
|
+
return f"{obj.content_type.app_label}.{obj.content_type.model}"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ActivityLogWidget:
|
|
26
|
+
"""
|
|
27
|
+
Widget for showing activity logs.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
col_span = 2
|
|
31
|
+
|
|
32
|
+
def get_data(self, request):
|
|
33
|
+
return LogEntrySerializer(
|
|
34
|
+
LogEntry.objects.all().order_by("-action_time")[0:5], many=True
|
|
35
|
+
).data
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
from decimal import Decimal
|
|
2
|
+
|
|
3
|
+
from django.db import models
|
|
4
|
+
from rest_framework.exceptions import ParseError
|
|
5
|
+
from rest_framework.filters import BaseFilterBackend
|
|
6
|
+
|
|
7
|
+
from .utils import flatten
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class LookupFilter(BaseFilterBackend):
|
|
11
|
+
"""
|
|
12
|
+
A permissive filter backend that basically allows every supported lookup
|
|
13
|
+
for a given field. Automatically handles multi-value lookups and booleans.
|
|
14
|
+
Also supports exclusion.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
MULTI_VALUE_LOOKUPS = ["in", "range"]
|
|
18
|
+
|
|
19
|
+
EXCLUDE_SYMBOL = "~"
|
|
20
|
+
|
|
21
|
+
NON_FILTER_FIELDS = [
|
|
22
|
+
"search",
|
|
23
|
+
"limit",
|
|
24
|
+
"page",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
def filter_queryset(self, request, queryset, view):
|
|
28
|
+
"""
|
|
29
|
+
Build the queryset based on the query params and the view's model.
|
|
30
|
+
Only apply filters in list endpoints.
|
|
31
|
+
"""
|
|
32
|
+
if getattr(view, "action", None) == "list":
|
|
33
|
+
try:
|
|
34
|
+
filter_kwargs, exclude_kwargs = self.get_filter_kwargs(
|
|
35
|
+
model_class=view.queryset.model,
|
|
36
|
+
query_params=request.query_params,
|
|
37
|
+
)
|
|
38
|
+
except Exception as e:
|
|
39
|
+
print(e)
|
|
40
|
+
raise ParseError(detail="Invalid filter parameters")
|
|
41
|
+
return queryset.filter(**filter_kwargs).exclude(**exclude_kwargs).distinct()
|
|
42
|
+
|
|
43
|
+
return queryset
|
|
44
|
+
|
|
45
|
+
def get_filter_kwargs(self, model_class, query_params):
|
|
46
|
+
filter_kwargs = {}
|
|
47
|
+
exclude_kwargs = {}
|
|
48
|
+
|
|
49
|
+
field_lookups = self.get_field_lookups(model_class=model_class)
|
|
50
|
+
|
|
51
|
+
for key, value in query_params.lists():
|
|
52
|
+
if key in self.NON_FILTER_FIELDS:
|
|
53
|
+
continue
|
|
54
|
+
# By default Django supports repeated multi-values (e.g. `a=1&a=2`)
|
|
55
|
+
# but we allow for comma-seperated multi-values as well (e.g. `a=1,2`).
|
|
56
|
+
value = flatten([param.split(",") for param in value])
|
|
57
|
+
is_exclude = key.startswith(self.EXCLUDE_SYMBOL)
|
|
58
|
+
# The first part of a key is considered the field name
|
|
59
|
+
field_name = key.split("__")[0]
|
|
60
|
+
# Get the model field.
|
|
61
|
+
field = model_class._meta.get_field(field_name)
|
|
62
|
+
# Get the allowed lookups for this field.
|
|
63
|
+
lookups = field_lookups.get(field_name, [])
|
|
64
|
+
try:
|
|
65
|
+
# The last part of a key is considered its lookup
|
|
66
|
+
# but it's not required.
|
|
67
|
+
lookup = key.split("__")[-1]
|
|
68
|
+
if lookup not in lookups:
|
|
69
|
+
lookup = None
|
|
70
|
+
except IndexError:
|
|
71
|
+
lookup = None
|
|
72
|
+
|
|
73
|
+
# Some lookups allow multiple values, otherwise
|
|
74
|
+
# the first value is used.
|
|
75
|
+
is_multi = lookup in self.MULTI_VALUE_LOOKUPS
|
|
76
|
+
# Depending on the field type we cast the value to
|
|
77
|
+
# its correct type (i.e. number, boolean, etc.).
|
|
78
|
+
if is_multi:
|
|
79
|
+
casted_value = [self.cast_field_value(v, field) for v in value]
|
|
80
|
+
elif lookup == "isnull":
|
|
81
|
+
casted_value = value[0] in ["1", "true", "on"]
|
|
82
|
+
else:
|
|
83
|
+
casted_value = self.cast_field_value(value[0], field)
|
|
84
|
+
|
|
85
|
+
if is_exclude:
|
|
86
|
+
exclude_kwargs[key] = casted_value
|
|
87
|
+
else:
|
|
88
|
+
filter_kwargs[key] = casted_value
|
|
89
|
+
|
|
90
|
+
return filter_kwargs, exclude_kwargs
|
|
91
|
+
|
|
92
|
+
@staticmethod
|
|
93
|
+
def get_field_lookups(model_class):
|
|
94
|
+
"""
|
|
95
|
+
Allow all supported lookups.
|
|
96
|
+
"""
|
|
97
|
+
field_lookups = {}
|
|
98
|
+
for model_field in model_class._meta.get_fields():
|
|
99
|
+
lookup_list = model_field.get_lookups().keys()
|
|
100
|
+
field_lookups[model_field.name] = lookup_list
|
|
101
|
+
return field_lookups
|
|
102
|
+
|
|
103
|
+
def cast_field_value(self, value: str, field):
|
|
104
|
+
value = value.strip().lower()
|
|
105
|
+
|
|
106
|
+
if isinstance(field, models.BooleanField):
|
|
107
|
+
if value in ["1", "true", "on"]:
|
|
108
|
+
return True
|
|
109
|
+
if value in ["0", "false", "off"]:
|
|
110
|
+
return False
|
|
111
|
+
if isinstance(field, models.NullBooleanField):
|
|
112
|
+
if value in ["null", "none", "empty"]:
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
if isinstance(field, models.IntegerField):
|
|
116
|
+
return int(value)
|
|
117
|
+
|
|
118
|
+
if isinstance(field, models.DecimalField):
|
|
119
|
+
return Decimal(value)
|
|
120
|
+
|
|
121
|
+
if isinstance(field, models.FloatField):
|
|
122
|
+
return float(value)
|
|
123
|
+
|
|
124
|
+
return value
|