Django role based views?

后端 未结 9 1987
既然无缘
既然无缘 2020-12-04 06:43

I\'m looking for some input on how others would architect this. I\'m going to provide class (django group) based views.

For example, a user\'s group will determine

9条回答
  •  离开以前
    2020-12-04 07:29

    I had a similar problem not too long ago. Our solution did the trick, though it might be too simple for your situation. Like everyone is suggesting, we used the django permission system to control what user interactions with models. However, we didn't just try to group users, we also grouped objects through a GenericForeignKey.

    We built a model that linked to itself to allow for hierarchies to be developed.

    class Group( models.Model ):
        name = models.CharField( ... )
        parent = models.ForeignKey( 'self', blank=True, null=True)
        content_type = models.ForeignKey( ContentType )
        object_id = models.PositiveIntegerField()
        content_object = generic.GenericForeignKey( 'content_type', 'object_id' )
        ...
    

    To make it work, we also created a model to serve as the django User model's user profile. All it contained was a ManyToManyField linked to the Group model above. This allowed us to give users access to zero or more Groups as required. (documentation)

    class UserProfile( models.Model ):
        user = models.ForeignKey( User, unique=True )
        groups = models.ManyToManyField( Group )
        ...
    

    This gave us the best of both worlds and kept us from trying to shoehorn everything into django's permission system. I'm using this basic setup to control user's access to sports content (some users can access whole leagues, some only one or two conferences, some only have access to individual teams), and it works well in that situation. It could probably be a generalized enough to fit your needs.

提交回复
热议问题