Debian Codegraph @

django_rq/admin.py

raw
1 from functools import wraps
2 from typing import Any, Optional
3
4 from django.contrib import admin
5 from django.http.request import HttpRequest
6 from django.http.response import HttpResponse
7
8 from . import models, settings, stats_views
9
10
11 class QueueAdmin(admin.ModelAdmin):
12 """Admin View for Django-RQ Queue"""
13
14 def has_add_permission(self, request):
15 return False # Hide the admin "+ Add" link for Queues
16
17 def has_change_permission(self, request: HttpRequest, obj: Optional[Any] = None) -> bool:
18 return True
19
20 def has_module_permission(self, request: HttpRequest):
21 """
22 return True if the given request has any permission in the given
23 app label.
24
25 Can be overridden by the user in subclasses. In such case it should
26 return True if the given request has permission to view the module on
27 the admin index page and access the module's index page. Overriding it
28 does not restrict access to the add, change or delete views. Use
29 `ModelAdmin.has_(add|change|delete)_permission` for that.
30 """
31 return request.user.has_module_perms('django_rq') # type: ignore[union-attr]
32
33 def changelist_view(self, request: HttpRequest, extra_context: Optional[dict[str, Any]] = None) -> HttpResponse:
34 """The 'change list' admin view for this model."""
35 # proxy request to stats view
36 return stats_views.stats(request)
37
38 def get_urls(self):
39 """
40 Register Django-RQ views within Django admin.
41
42 URLs will be available at /admin/django_rq/dashboard/<pattern>/
43 This provides automatic integration without requiring users to edit urls.py.
44
45 Uses two sets of URL patterns:
46 - API patterns (stats_json, prometheus_metrics): NOT wrapped, support API token auth
47 - Admin patterns (all other views): Wrapped with admin_view for session auth
48 """
49 # Import inside method to avoid circular imports
50 from .urls import get_admin_urlpatterns, get_api_urlpatterns
51
52 def wrap(view):
53 """Wrap view with admin_site.admin_view for permission checking"""
54
55 @wraps(view)
56 def wrapper(request, *args, **kwargs):
57 request.current_app = self.admin_site.name
58 return self.admin_site.admin_view(view)(request, *args, **kwargs)
59
60 return wrapper
61
62 # Get both sets of URL patterns
63 api_urls = get_api_urlpatterns(name_prefix='django_rq_') # Not wrapped - have their own auth
64 admin_urls = get_admin_urlpatterns(name_prefix='django_rq_', view_wrapper=wrap) # Wrapped with admin auth
65
66 # Combine and add to standard ModelAdmin URLs
67 return api_urls + admin_urls + super().get_urls()
68
69
70 # Register the Dashboard model with admin if enabled.
71 if settings.SHOW_ADMIN_LINK:
72 admin.site.register(models.Dashboard, QueueAdmin)