Opened 102 minutes ago
Closed 5 minutes ago
#37021 closed New feature (needsnewfeatureprocess)
Add a helper function to return the permission string representation to be used with `user.has_perm()`
| Reported by: | Mariatta | Owned by: | |
|---|---|---|---|
| Component: | contrib.auth | Version: | 6.0 |
| Severity: | Normal | Keywords: | codename, has_perm |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description (last modified by )
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.
Change History (2)
comment:1 by , 101 minutes ago
| Description: | modified (diff) |
|---|
comment:2 by , 5 minutes ago
| Keywords: | codename has_perm added |
|---|---|
| Resolution: | → needsnewfeatureprocess |
| Status: | new → closed |
Thanks for the idea. I'm very tempted to accept this, because the lack of this feature can lead to the temptation to hard-code the app label. (#26547 points out this is incorrect if the
AppConfigoverrides the label).However, although it's just a one-liner, forcing the user to write it themselves will probably alert them to the need to JOIN the content types, or otherwise do an annotation, to avoid an N+1 query problem.
As silly as it might sound to go through the new feature process for this, I think getting some confirming views there would be useful. Can I ask you to repeat your request there, and mention the temptation to do it the "wrong" way by hard-coding the app label?