File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -79,6 +79,11 @@ class Meta:
7979 def __str__ (self ):
8080 return "%s | %s" % (self .content_type , self .name )
8181
82+ @property
83+ def user_perm_str (self ):
84+ """String representation for the user permission check."""
85+ return f"{ self .content_type .app_label } .{ self .codename } "
86+
8287 def natural_key (self ):
8388 return (self .codename , * self .content_type .natural_key ())
8489
Original file line number Diff line number Diff line change @@ -405,6 +405,16 @@ Methods
405405:class:`~django.contrib.auth.models.Permission` objects have the standard
406406data-access methods like any other :doc:`Django model </ref/models/instances>`.
407407
408+ .. class:: models.Permission
409+ :noindex:
410+
411+ .. attribute:: user_perm_str
412+
413+ .. versionadded:: 6.1
414+
415+ Returns the string representation for use in :meth:`has_perm
416+ <django.contrib.auth.models.User.has_perm>`.
417+
408418``Group`` model
409419===============
410420
Original file line number Diff line number Diff line change @@ -129,6 +129,9 @@ Minor features
129129* :attr:`.Permission.name` and :attr:`.Permission.codename` values are now
130130 renamed when renaming models via a migration.
131131
132+ * The new :attr:`.Permission.user_perm_str` property returns the string
133+ suitable to use with :meth:`.User.has_perm`.
134+
132135:mod:`django.contrib.contenttypes`
133136~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
134137
Original file line number Diff line number Diff line change @@ -243,6 +243,15 @@ to test for basic permissions you should use:
243243The :class:`~django.contrib.auth.models.Permission` model is rarely accessed
244244directly.
245245
246+ The :class:`~django.contrib.auth.models.Permission` model provides a helper
247+ property, :attr:`~django.contrib.auth.models.Permission.user_perm_str`,
248+ that returns the string representation that can be used to check permission
249+ using the :meth:`~django.contrib.auth.models.User.has_perm` method.
250+
251+ .. versionchanged:: 6.1
252+
253+ The ``user_perm_str`` property was added.
254+
246255Groups
247256------
248257
Original file line number Diff line number Diff line change @@ -635,3 +635,7 @@ def test_str(self):
635635 self .assertEqual (
636636 str (p ), "Auth_Tests | custom email field | Can view custom email field"
637637 )
638+
639+ def test_user_perm_str (self ):
640+ p = Permission .objects .get (codename = "view_customemailfield" )
641+ self .assertEqual (p .user_perm_str , "auth_tests.view_customemailfield" )
You can’t perform that action at this time.
0 commit comments