5.7. Admin Abstract
>>>
... from django.contrib import admin
...
... class BaseAdmin(admin.ModelAdmin):
... pass
5.7.1. Use Case - 1
>>>
... from django.contrib import admin
... from django.http import HttpRequest
... from django.utils.translation import gettext_lazy as _
...
...
... class BaseAdmin(admin.ModelAdmin):
... def get_queryset(self, request: HttpRequest):
... qs = super().get_queryset(request)
... if request.user.is_superuser:
... return qs
... return qs.filter(is_deleted=False)
...
... def get_readonly_fields(self, request: HttpRequest, obj: admin.ModelAdmin | None = None):
... readonly_fields = super().get_readonly_fields(request, obj)
... readonly_fields += ('uuid', 'created_date', 'created_user', 'modified_date', 'modified_user', 'is_deleted')
... return readonly_fields
...
... def get_list_display(self, request: HttpRequest):
... list_display = super().get_list_display(request)
... if request.user.is_superuser and 'is_deleted' not in list_display:
... list_display.insert(0, 'is_deleted')
... return list_display
...
... def save_model(self, request: HttpRequest, obj: admin.ModelAdmin, form, change: bool):
... if not change:
... obj.created_user = request.user
... obj.modified_user = request.user
... return super().save_model(request, obj, form, change)
...
... def delete_model(self, request, obj):
... obj.is_deleted = True
... obj.save()
5.7.2. Use Cae - 0x02
>>>
... from django.contrib import admin
... from django.utils.translation import gettext_lazy as _
...
...
... admin.site.site_header = _('Dashboard') # w nagłówku panelu administracyjnego
... admin.site.site_title = _('My Project') # w tytule karty przeglądarki
... admin.site.index_title = _('Index Title') # nazwa aplikacji na głównej stronie panelu administracyjnego
...
...
... class BaseAdmin(admin.ModelAdmin):
... def get_queryset(self, request):
... qs = super().get_queryset(request)
... if request.user.is_superuser:
... return qs.all()
... return qs.filter(is_deleted=False)
...
... def get_list_display(self, request):
... list_display = list(super().get_list_display(request))
... if request.user.is_superuser:
... additional_fields = ['is_deleted', 'created_user', 'modified_user']
... return list_display + additional_fields
... return list_display
...
... def get_list_filter(self, request):
... list_filter = list(super().get_list_filter(request))
... if request.user.is_superuser:
... additional_fields = ['is_deleted', 'created_user', 'modified_user']
... return list_filter + additional_fields
... return list_filter
...
... def save_model(self, request, obj, form, change: bool):
... if not change:
... # set created_user only when new object is created
... obj.created_user = request.user
... # set modified_user for both new and modified objects
... obj.modified_user = request.user
... return super().save_model(request, obj, form, change)
...
... def delete_model(self, request, obj):
... obj.is_deleted = True
... return obj.save()