Question

So django claims groups as "A generic way of applying labels and permissions to more than one user". My question is what this code looks like and where does this code live?

Specifically, do groups require and type of models? Any help in uncovering how these work would be very helpful.

PS: How do you apply a group to a currently logged in user?

Thanks for the help.

Was it helpful?

Solution

Groups are nothing but models.

class Player(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()

Above, the Player model is for adding players. Now, if you want to group those players into teams, you'd do something like below:

class Team(models.Model):
    players = models.ManyToManyField(Player)
    team_name = models.CharField(max_length=100) 

Now, you just have to create a team and keep adding players to it. Pretty easy, right?

Okay fine until now. Let's say, there were 4 matches today which means 8 teams played those matches. Out of the total players who played today, 15 got injured, and 10 got banned from playing the next match. So if you want to make groups for injured and banned players, you would do something like below:

class Injured(models.Model):
     players = models.ManyToManyField(Player)

class Banned(models.Model):
    players = models.ManyToManyField(Player)

That's it.

Now, the question is why would you use groups?

Of course, there's no need of writing group models, you have other options too.

class Player(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()
    team = models.CharField(max_length=100)
    is_injured = models.BooleanField(default=False)
    is_banned = models.BooleanField(default=False)

Now think: 15 players were injured, which means you would have to update 15 players' is_injured to True. 8 were banned, which means you'd have to change 8 players' is_banned to True. Plus, you'd have to keep writing the name of every player's team again and again. It is really very time consuming. Now do you see the importance of groups?

Where does this code live?

In your models.py file.

OTHER TIPS

User groups are part of 'django.contrib.auth'. If you are using it with your user model (any normal user in Django 1.4 and lower, or custom user model WITH "PermissionsMixin" in Django 1.5 or higher), then you will find respective tables in your database named:

  • auth_group
  • auth_group_permissions
  • auth_permission
  • auth_user_groups
  • auth_user_user_permissions

Each user gets all the permissions set

  • to groups (auth_groups) that are assigned to the user in the auth_user_groups table
  • for the user in the auth_user_user_permissions

See django.contrib.aut for more information.

Adding user to groups was explained in this post

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top