I have a django app. And I added in the admin panel of django the following permission:
Accounts | account | Can view account
And in the code of admin.py of the accounts app. I added this:
from django.contrib.auth import get_user_model
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from .models import Account
User = get_user_model()
user = User.objects.get(email='[email protected]')
content_type = ContentType.objects.get_for_model(Account)
permission = Permission.objects.get(
codename='view_account', content_type=content_type)
user.user_permissions.add(permission)
class AccountAdmin(UserAdmin):
list_display = (
"email",
"first_name",
"last_name",
"username",
"last_login",
"date_joined",
"is_active",
)
list_display_links = ("email", "first_name", "last_name")
filter_horizontal = (
'groups',
'user_permissions',
)
readonly_fields = ("last_login", "date_joined")
ordering = ("-date_joined",)
list_filter = ()
User = get_user_model()
user = User.objects.get(email='[email protected]')
content_type = ContentType.objects.get_for_model(Account)
permission = Permission.objects.get(
codename='view_account', content_type=content_type)
user.user_permissions.add(permission)
admin.site.register(Account, AccountAdmin)
And when I start the django app. I don’t get any errors.
But when I login with the account with the user permission. I still see the message:
You don’t have permission to view or edit anything.
And the permissions:
- Is active
- Is staff
are selected
Question: how to add permissions for users?