Opened 7 years ago

Last modified 7 years ago

#28140 new New feature

Add convenience method to add `Permission`s to a `User`

Reported by: Flavio Curella Owned by: nobody
Component: contrib.auth Version: 1.11
Severity: Normal Keywords:
Cc: Triage Stage: Someday/Maybe
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When writing tests checking for permissions, it's commonplace to test if a user can access a particular view, check for failure, add the necessary permission, then check again for success:

def mytest(self):
    user = User.objects.create_user(
            username='regularuser',
            password='regularuser',
    )
    response = self.client.get('/mymodel/create/')
    # Usually redirects to some other page, such as `/login/`
    self.assertNotEqual(response.status_code, 200)

    # then we fetch the 'myapp.add_mymodel' permission and add it to `user`
    my_permission = Permission.objects.get_by_natural_key('add_mymodel', 'myapp', 'mymodel')
    user.user_permissions.add(mypermission)

    response = self.client.get('/mymodel/create/')
    # now it works
    self.assertEqual(response.status_code, 200)

I'm wondering if we should have a more convenient way to add permissions. I'm thinking of adding a add_perm method to the User model, that mirrors the already existing `has_perm` so that instead of

    my_permission = Permission.objects.get_by_natural_key('add_mymodel', 'myapp', 'mymodel')
    user.user_permissions.add(mypermission)

    response = self.client.get('/mymodel/create/')
    self.assertEqual(response.status_code, 200)

we can have:

    user.add_perm('myapp.add_mymodel')
    response = self.client.get('/mymodel/create/')
    self.assertEqual(response.status_code, 200)

Change History (3)

comment:1 by Tim Graham, 7 years ago

Triage Stage: UnreviewedSomeday/Maybe

There's the problem described in #25281 that "<app label>.<permission codename>" might not uniquely identify permissions. Anyway, a proposal like this should be made on the DevelopersMailingList to see if there's consensus, however, the existence of a helper in Django's test suite to help ease the verbosity here is a good indication that something could be done. I'm bit confused because the ticket's summary talks about adding a manager method to Permission but the description proposes adding a user method. In the latter case, a consideration of custom user models might be needed.

comment:2 by Flavio Curella, 7 years ago

Summary: Add convenience manager method to `Permission`sAdd convenience method to add `Permission`s to a `User`

comment:3 by Flavio Curella, 7 years ago

Thank Tim,

I will work on a proposal for #25281. Once that's resolve, I can move on to this one.

Version 0, edited 7 years ago by Flavio Curella (next)
Note: See TracTickets for help on using tickets.
Back to Top