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

后端 未结 6 1087
小鲜肉
小鲜肉 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:06

    For those of you, who are still searching:

    You can create an auxiliary model with no database table. That model can bring to your project any permission you need. There is no need to deal with ContentType or create Permission objects explicitly.

    from django.db import models
            
    class RightsSupport(models.Model):
                
        class Meta:
            
            managed = False  # No database table creation or deletion  \
                             # operations will be performed for this model. 
                    
            default_permissions = () # disable "add", "change", "delete"
                                     # and "view" default permissions
    
            permissions = ( 
                ('customer_rights', 'Global customer rights'),  
                ('vendor_rights', 'Global vendor rights'), 
                ('any_rights', 'Global any rights'), 
            )
    

    Right after manage.py makemigrations and manage.py migrate you can use these permissions like any other.

    # Decorator
    
    @permission_required('app.customer_rights')
    def my_search_view(request):
        …
    
    # Inside a view
    
    def my_search_view(request):
        request.user.has_perm('app.customer_rights')
    
    # In a template
    # The currently logged-in user’s permissions are stored in the template variable {{ perms }}
    
    {% if perms.app.customer_rights %}
        

    You can do any customer stuff

    {% endif %}

提交回复
热议问题