How can I use Django permissions without defining a content type or model?

后端 未结 6 1090
小鲜肉
小鲜肉 2021-01-29 18:56

I\'d like to use a permissions based system to restrict certain actions within my Django application. These actions need not be related to a particular model (e.g. access to sec

6条回答
  •  再見小時候
    2021-01-29 19:03

    This is alternative solution. First ask yourself: Why not create a Dummy-Model which really exists in DB but never ever gets used, except for holding permissions? That's not nice, but I think it is valid and straight forward solution.

    from django.db import models
    
    class Permissions(models.Model):
    
        can_search_blue_flower = 'my_app.can_search_blue_flower'
    
        class Meta:
            permissions = [
                ('can_search_blue_flower', 'Allowed to search for the blue flower'),
            ]
    

    Above solution has the benefit, that you can use the variable Permissions.can_search_blue_flower in your source code instead of using the literal string "my_app.can_search_blue_flower". This means less typos and more autocomplete in IDE.

提交回复
热议问题