Extending django groups and permissions

I searched Google and Stackoverflow for the last 3 days and did not find anything like it. I would like to expand or use django groups and permissions.

Let's say we have several projects with different teams and users.

class Project(models.Model): owner = models.ForeignKey(User) name = models.CharField(max_length=100) class Team(models.Model): project = models.ForeignKey(Project) members = models.ManyToManyField(User) name = models.CharField(max_length=100) permission = models.ManyToManyField(Permission) 

Now everything is fine. Now I want to extend the existing Auth.Group supplied by django so that I can use request.user.has_perm... direct path.

So change Team-Model to

 class Team(Group): project = models.ForeignKey(Project) members = models.ManyToManyField(User) 

This extends the existing group. The name and permissions field comes directly from the model group. If I create a new team, a group will be added. It's great.

Using the special save method, I could add that the user specified in members will be added to the created group and will receive the permissions granted to the team / group.

Now my problem is that the group name field is unique - so I could not add the Admins command for each project.

I thought about adding another name field for the interface and creating a unique string for the Group-Model name field. But hmm ... is there a better solution for multiple user groups? Maybe you have an idea? Thank you in advance!

+5
django django-models django-permissions
source share
1 answer

You need group names to be unique. Thus, one of the ways that you learned is a different name field, which makes it unique for all subgroups.

Another way is to use an existing name field and add special characters. For example, the name of the group with admin#project1 , members#project1 , etc. (Note: I am not sure that "#" is allowed in the group name, you can select any special character that is allowed).

Therefore, whenever you create a Team , you update the name field with the suffix #<project_name> in the save() model Team method.

To display it more safely, you can add the __unicode__() method to return only the first part of the group name. Example:

 class Team(Group): ... def __unicode__(self): try: return self.name.split('#')[0] except: #something wrong! return self.name 
+2
source share

All Articles