Django - user permissions to certain views?

后端 未结 5 916
夕颜
夕颜 2020-12-14 01:45

From the admin I see that you can allocate permissions to a user or a user group to :allow add, change or delete data from a model.

That is great, but I also need t

5条回答
  •  青春惊慌失措
    2020-12-14 02:17

    Users that cannot add or change etc. a certain model, will not be able to see it in the admin.

    If we are talking about your custom created views then you could create something which checks a user for a permission and returns a 404 if they do not have that permission. Permissions are linked to models and a group can be assigned various permissions.

    You can add a permission to a model like this:

    # myproject/myapp/models.py
    
    class MyModel(models.Model):
        class Meta:
            permissions = (
                ('permission_code', 'Friendly permission description'),
            )
    

    Then you can check a if a user has permission like this:

    @user_passes_test(lambda u: u.has_perm('myapp.permission_code'))
    def some_view(request):
        # ...
    

    Using permissions you can then easily add or remove them from users and groups simply using the admin interface.

提交回复
热议问题