I facing trouble with adding a branch/department to user groups. Please help.
I need to grant user A to group ‘counselor’ on branch 1
and same user A to group ‘admin’ on branch 2
Please advise how to write a model and query for this case.
I really appreciate any help you can provide.
Thank you for your reply.
In Django, user permissions and user groups there is no field for branch/department.
So group xyz is granted to me, but only in branch 1, how can I add the branch field to the user_group table. if user_group is: id, user_id, group_id. I want to add branch_id as well to this table.
After adding the field, I think I need to write a custom permission class to handle the branch ID.
Please help.
You really need to provide a lot more detail about what your objectives are. Brief statements like this do not convey sufficient information for me to understand what you’re trying to achieve.
You have not shown any models. You have not defined what you mean by something being “granted to”. You have not identified what these “branches” are. If you’re looking for assistance here, you’re going to need to really explain the situation.
Generally speaking, no. The existing permission system is flexible enough to handle anything you’re likely to encounter.
from user.models import User
from django.contrib.auth.models import Group
class Branch(models.Model):
company = models.ForeignKey(Company, on_delete=models.DO_NOTHING)
branch_name = models.CharField(max_length=30, unique=True)
class Meta:
ordering = ['branch_name']
def __str__(self):
return self.branch_name
class Group_Branch(models.Model):
group = models.OneToOneField(Group, on_delete=models.CASCADE)
branch = models.ForeignKey(Branch, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
I don’t know what the desired result is, so I can’t answer your questions. I have asked twice for you to provide sufficient information to allow me to guide you but you have not responded to those requests. It would not be responsible for me to offer opinion regarding the “correctness” of code without understanding your requirements and objectives.
I’m so sorry for not being clear and sorry for any inconvenience.
I meant to add Group_Branch model that have django.contrib.auth.models.group, branch, and user
as shown below
class Group_Branch(models.Model):
group = models.OneToOneField(Group, on_delete=models.CASCADE)
branch = models.ForeignKey(Branch, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
Or just add branch field to Group model like:
from django.contrib.auth.models import AbstractGroup // something like this
class Group_Branch(AbstractGroup): // new group name
branch = models.ForeignKey(Branch, on_delete=models.CASCADE)
So I can assign user access to group+branch (using admin page).
Hope it is somehow better.
Thanks.