You need to ensure that the user has the necessary permissions to access the custom view. You can do this by overriding the has_module_permission method in your ActivationCodeAdmin class and ensuring that the custom view respects the user’s permissions.
from django.contrib import admin
from django.urls import path
from django.http import HttpResponse
from .models import ActivationCode
class ActivationCodeAdmin(admin.ModelAdmin):
change_list_template = 'admin/my_change_list.html'
def get_urls(self):
urls = super().get_urls()
custom_urls = [
path('generate_activation_codes/', self.admin_site.admin_view(self.generate_activation_codes), name='generate_activation_codes'),
]
return custom_urls + urls
def generate_activation_codes(self, request):
# Check if the user has the permission to add activation codes
if not self.has_add_permission(request):
self.message_user(request, "You do not have permission to generate activation codes.", level='error')
return HttpResponse(status=403)
# Your logic to generate activation codes
# ...
self.message_user(request, "Activation codes generated successfully.")
return HttpResponse("Activation codes generated successfully.")
def has_module_permission(self, request):
"""
Return True if the user has permission to view the app.
"""
return request.user.has_perm('activation.view_activationcode')
admin.site.register(ActivationCode, ActivationCodeAdmin)
Set the appropriate permissions set up in your models.py for the ActivationCode model:
from django.db import models
class ActivationCode(models.Model):
# Your model fields
# ...
class Meta:
permissions = [
("view_activationcode", "Can view activation code"),
("add_activationcode", "Can add activation code"),
("change_activationcode", "Can change activation code"),
("delete_activationcode", "Can delete activation code"),
]