-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.py
More file actions
314 lines (262 loc) · 12.3 KB
/
admin.py
File metadata and controls
314 lines (262 loc) · 12.3 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""Admin page configuration for the learning-credentials app."""
from __future__ import annotations
import importlib
import inspect
from typing import TYPE_CHECKING
import django
from django import forms
from django.contrib import admin, messages
from django.core.exceptions import ValidationError
from django.db.models import URLField
from django.urls import reverse
from django.utils.html import format_html
from django_object_actions import DjangoObjectActions, action
from django_reverse_admin import ReverseModelAdmin
from learning_paths.keys import LearningPathKey
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from .models import (
Credential,
CredentialAsset,
CredentialConfiguration,
CredentialType,
)
from .tasks import generate_credentials_for_config_task
if TYPE_CHECKING: # pragma: no cover
from collections.abc import Generator
from django.http import HttpRequest
from django_celery_beat.models import IntervalSchedule
class DocstringOptionsMixin:
"""A mixin to add the docstring of the function to the help text of the function field."""
@staticmethod
def _get_docstring_custom_options(func: str) -> str:
"""
Get the docstring of the function and return the "Options:" section.
:param func: The function to get the docstring for.
:returns: The "Options:" section of the docstring.
"""
try:
docstring = (
'Custom options:'
+ inspect.getdoc(
getattr(
importlib.import_module(func.rsplit('.', 1)[0]),
func.rsplit('.', 1)[1],
),
).split("Options:")[1]
)
except IndexError:
docstring = (
'Custom options are not documented for this function. If you selected a different function, '
'you need to save your changes to see an updated docstring.'
)
# Use pre to preserve the newlines and indentation.
return f'<pre>{docstring}</pre>'
class CredentialTypeAdminForm(forms.ModelForm, DocstringOptionsMixin):
"""Generate a list of available functions for the function fields."""
retrieval_func = forms.ChoiceField(choices=[])
generation_func = forms.ChoiceField(choices=[])
@staticmethod
def _available_functions(module: str, prefix: str) -> Generator[tuple[str, str], None, None]:
"""
Import a module and return all functions in it that start with a specific prefix.
:param module: The name of the module to import.
:param prefix: The prefix of the function names to return.
:return: A tuple containing the functions that start with the prefix in the module.
"""
# TODO: Implement plugin support for the functions.
_module = importlib.import_module(module)
return (
(f'{obj.__module__}.{name}', f'{obj.__module__}.{name}')
for name, obj in inspect.getmembers(_module, inspect.isfunction)
if name.startswith(prefix)
)
def __init__(self, *args, **kwargs):
"""Initializes the choices for the retrieval and generation function selection fields."""
super().__init__(*args, **kwargs)
self.fields['retrieval_func'].choices = self._available_functions(
'learning_credentials.processors',
'retrieve_',
)
if self.instance.retrieval_func:
self.fields['retrieval_func'].help_text = self._get_docstring_custom_options(self.instance.retrieval_func)
self.fields['generation_func'].choices = self._available_functions(
'learning_credentials.generators',
'generate_',
)
if self.instance.generation_func:
self.fields['generation_func'].help_text = self._get_docstring_custom_options(self.instance.generation_func)
class Meta: # noqa: D106
model = CredentialType
fields = '__all__' # noqa: DJ007
@admin.register(CredentialType)
class CredentialTypeAdmin(admin.ModelAdmin): # noqa: D101
form = CredentialTypeAdminForm
list_display = ('name', 'retrieval_func', 'generation_func')
@admin.register(CredentialAsset)
class CredentialAssetAdmin(admin.ModelAdmin): # noqa: D101
list_display = ('description', 'asset_slug')
prepopulated_fields = {"asset_slug": ("description",)} # noqa: RUF012
class CredentialConfigurationForm(forms.ModelForm, DocstringOptionsMixin): # noqa: D101
class Meta: # noqa: D106
model = CredentialConfiguration
fields = ('learning_context_key', 'credential_type', 'custom_options')
def __init__(self, *args, **kwargs):
"""Initializes the choices for the retrieval and generation function selection fields."""
super().__init__(*args, **kwargs)
options = ''
if self.instance and getattr(self.instance, 'credential_type', None):
if self.instance.credential_type.generation_func:
generation_options = self._get_docstring_custom_options(self.instance.credential_type.generation_func)
options += generation_options.replace('Custom options:', '\nGeneration options:')
if self.instance.credential_type.retrieval_func:
retrieval_options = self._get_docstring_custom_options(self.instance.credential_type.retrieval_func)
options += retrieval_options.replace('Custom options:', '\nRetrieval options:')
self.fields['custom_options'].help_text += options
def clean_learning_context_key(self) -> str:
"""Validate the learning_context_key field to ensure it is a valid CourseKey or LearningPathKey."""
learning_context_key = self.cleaned_data.get('learning_context_key')
try:
try:
CourseKey.from_string(learning_context_key)
except InvalidKeyError:
LearningPathKey.from_string(learning_context_key)
except InvalidKeyError as exc:
msg = (
"Invalid key format. Must be either a valid course key ('course-v1:{org}+{course}+{run}') "
"or a valid Learning Path key ('path-v1:{org}+{number}+{run}+{group}')."
)
raise ValidationError(msg) from exc
return learning_context_key
@admin.register(CredentialConfiguration)
class CredentialConfigurationAdmin(DjangoObjectActions, ReverseModelAdmin):
"""
Admin page for the context-specific credential configuration for each credential type.
It manages the associations between configuration and its corresponding periodic task.
The reverse inline provides a way to manage the periodic task from the configuration page.
"""
form = CredentialConfigurationForm
inline_type = 'stacked'
inline_reverse = [ # noqa: RUF012
(
'periodic_task',
{'fields': ['enabled', 'interval', 'crontab', 'clocked', 'start_time', 'expires', 'one_off']},
),
]
list_display = ('learning_context_key', 'credential_type', 'enabled', 'interval')
search_fields = ('learning_context_key', 'credential_type__name')
list_filter = ('learning_context_key', 'credential_type')
def get_inline_instances(
self,
request: HttpRequest,
obj: CredentialConfiguration = None,
) -> list[admin.ModelAdmin]:
"""
Hide inlines on the "Add" view in Django admin, and show them on the "Change" view.
It differentiates "add" and change "view" based on the requested path because the `obj` parameter can be `None`
in the "Change" view when rendering the inlines.
:param request: HttpRequest object
:param obj: The object being changed, None for add view
:return: A list of InlineModelAdmin instances to be rendered for add/changing an object
"""
return super().get_inline_instances(request, obj) if '/add/' not in request.path else []
def enabled(self, obj: CredentialConfiguration) -> bool:
"""Return the 'enabled' status of the periodic task."""
return obj.periodic_task.enabled
enabled.boolean = True
# noinspection PyMethodMayBeStatic
def interval(self, obj: CredentialConfiguration) -> IntervalSchedule:
"""Return the interval of the credentialedential generation task."""
return obj.periodic_task.interval
def get_readonly_fields(self, _request: HttpRequest, obj: CredentialConfiguration = None) -> tuple:
"""Make the learning_context_key field read-only."""
if obj: # editing an existing object
return *self.readonly_fields, 'learning_context_key', 'credential_type'
return self.readonly_fields
@action(label="Generate credentials")
def generate_credentials(self, _request: HttpRequest, obj: CredentialConfiguration):
"""
Custom action to generate credential for the current CredentialConfiguration instance.
Args:
_request: The request object.
obj: The CredentialConfiguration instance.
"""
generate_credentials_for_config_task.delay(obj.id)
change_actions = ('generate_credentials',)
@admin.register(Credential)
class CredentialAdmin(DjangoObjectActions, admin.ModelAdmin): # noqa: D101
list_display = (
'user',
'user_full_name',
'configuration',
'status',
'url',
'created',
'modified',
)
readonly_fields = (
'uuid',
'verify_uuid',
'user',
'configuration',
'created',
'modified',
'user_full_name',
'learning_context_name',
'status',
'url',
'legacy_id',
'generation_task_id',
)
search_fields = (
"configuration__learning_context_key",
"user_full_name",
"user__username",
"user__email",
"uuid",
"verify_uuid",
)
list_filter = ("configuration__learning_context_key", "configuration__credential_type", "status")
change_actions = ('reissue_credential',)
def save_model(self, request: HttpRequest, obj: Credential, _form: forms.ModelForm, _change: bool): # noqa: FBT001
"""Display validation errors as messages in the admin interface."""
try:
obj.save()
except ValidationError as e:
self.message_user(request, e.message or "Invalid data", level=messages.ERROR)
# Optionally, redirect to the change form with the error message
return
def get_form(self, request: HttpRequest, obj: Credential | None = None, **kwargs) -> forms.ModelForm:
"""Hide the download_url field."""
form = super().get_form(request, obj, **kwargs)
form.base_fields['download_url'].widget = forms.HiddenInput()
return form
# noinspection PyMethodMayBeStatic
def url(self, obj: Credential) -> str:
"""Display the download URL as a clickable link."""
if obj.download_url:
return format_html("<a href='{url}'>{url}</a>", url=obj.download_url)
return "-"
@action(label="Reissue credential", description="Reissue the credential for the user.")
def reissue_credential(self, request: HttpRequest, obj: Credential):
"""Reissue the credential for the user."""
new_credential = obj.reissue()
admin_url = reverse('admin:learning_credentials_credential_change', args=[new_credential.pk])
message = format_html(
'The credential has been reissued as <a href="{}">{}</a>.', admin_url, new_credential.uuid
)
messages.success(request, message)
def has_add_permission(self, _request: HttpRequest) -> bool:
"""Hide the "Add" button in the admin interface."""
return False
def has_delete_permission(self, _request: HttpRequest, _obj: Credential | None = None) -> bool:
"""Hide the "Delete" button in the admin interface."""
return False
def formfield_for_dbfield(self, db_field, request, **kwargs): # noqa: ANN001, ANN201
"""
Assume HTTPS for scheme-less domains pasted into URLFields.
This method can be removed when support for Django versions below 5.0 is dropped.
"""
if django.VERSION[0] > 4 and isinstance(db_field, URLField): # pragma: no cover
kwargs["assume_scheme"] = "https"
return super().formfield_for_dbfield(db_field, request, **kwargs)