-
Notifications
You must be signed in to change notification settings - Fork 6
Add a helper function to return the permission string representation to be used with user.has_perm() #137
Description
Code of Conduct
- I agree to follow Django's Code of Conduct
Feature Description
Originally opened in https://code.djangoproject.com/ticket/37021, and was told to create it here.
When checking user's permission using user.has_perm(), I need to pass a string in the format of {Permission.content_type.app_label}.{Permission.codename}
However, the Permission object itself does not provide an easy way to return this string.
The __str__ method of the Permission class returns a string of content_type | name.
I think it would be great if the Permission class can provide the string representation that will allow us to check the permission without having to manually construct it ourselves.
My desired outcome is to be able to do the following.
user_permissions = Permission.objects.filter(...)
for perm in user_permissions:
if user.has_perm(perm.perm_string()):
# let them do stuff
Currently I am doing it as follows:
if user.has_perm(f"{perm.content_type.app_label}.{perm.codename}"):
# let them do stuff
Proposal:
To add a function within Permission class:
def perm_string(self): # feel free to suggest other name
return f"{self.content_type.app_label}.{self.codename}"
If you agree, I would like to try to create the PR for this.
See also related ticket https://code.djangoproject.com/ticket/26547
In the related ticket, the proposal was to modify the user.has_perm() function and adding new parameters.
I think adding the helper function to the Permission object is cleaner.
Problem
I need a consistent way to check for user permission (user.has_perm()) for a given Permission object.
Currently I am doing it as follows:
if user.has_perm(f"{perm.content_type.app_label}.{perm.codename}"):
# let them do stuff
It would be great if the Permission class provides the string representation needed for the user permission check, so that I don't have to construct it myself.
Request or proposal
proposal
Additional Details
No response
Implementation Suggestions
To add a function within Permission class:
def perm_string(self): # feel free to suggest other name
return f"{self.content_type.app_label}.{self.codename}"
Metadata
Metadata
Assignees
Labels
Type
Projects
Status