40

I'd like to be able to give some existing Users a custom permission which I will require for accessing a view.

I think I need to add the new permission to the Postgres table auth_permission, but I suspect there is a higher-level way to do this. Also there is a column in auth_permission for content_type and I don't know what its value should be.

What is the right way to do this?

Mitch
  • 2,350
  • 7
  • 29
  • 48

1 Answers1

59

Have a look at how to create custom permissions in the docs.

class USCitizen(models.Model):
    # ...
    class Meta:
        permissions = (
            ("can_drive", "Can drive"),
            ("can_vote", "Can vote in elections"),
            ("can_drink", "Can drink alcohol"),
        )

Then run python manage.py makemigrations && python manage.py migrate.

Use the permission_required decorator to restrict access to your view.

Jack
  • 2,891
  • 11
  • 48
  • 65
sheats
  • 33,062
  • 15
  • 45
  • 44
  • Thanks. That worked. What initially confused me was that it creates a new model just for the permission. But I guess that makes sense. – Mitch Dec 09 '09 at 20:32
  • 2
    this didn't work for me. I changed the tuple to a list and it worked. The permissions looked like. permissions = [ ("",""),("","")] – Ritesh Jung Thapa Jul 21 '20 at 10:45
  • How do you dynamically make this in the VUE UI? – Grizzly Bear Oct 06 '20 at 15:10
  • Ritesh above is correct, as also confirmed by the docs, at least for current Django version 3.2 https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#custom-permissions – Hrafn Malmquist Nov 24 '21 at 13:26