I'm trying to figure out how to create custom groups in Django, in way that groups are related to application and not to a Project.
For example when a user want to create a company, it should be the owner of the company:
model
class Company(models.Model):
owner = models.ForeignKey(User)
name = models.CharField(max_length=64, unique=True)
description = models.TextField(max_length=512)
created_on = models.DateTimeField(auto_now_add=timezone.now)
class Meta:
permissions = (
("erp_view_company", "Can see the company information"),
("erp_edit_company", "Can edit the company information"),
("erp_delete_company", "Can delete the company"),
)
view
# Create your views here.
def register(request, template_name='erp/register.html'):
if request.method == 'POST':
company_form = CompanyRegistrationForm(request.POST)
if company_form.is_valid():
# Create a new company object but avoid saving it yet
new_company = company_form.save(commit=False)
# Set the owner
if request.user.is_authenticated():
new_company.owner = request.user
# Add the user to group admin
group = Group.objects.get_or_create(name="erp_admin")
request.user.groups.add(group)
# Save the User object
new_company.save()
template_name = 'erp/register_done.html'
return render(request, template_name, {'new_company': new_company})
else:
company_form = CompanyRegistrationForm()
return render(request, template_name, {'company_form': company_form})
Here the questions:
1) Instead of having Group.objects.get_or_create(name="erp_admin")
I'd like to have CompanyGroup.objects.get_or_create(name="admin")
in way that the Groups of an application are restricted to the application.
2) How I can map the permissions defined in the Meta class of each model to a group?
3) The custom groups are related to a Company, this mean each company has the group Admin, that starts with the owner. The owner can creates user like "Manager". The manager can creates groups/permissions, add user, set permission to user but can't in anyway CRUD the admin groups. So there's a kind of hierarchy in groups (I suppose that the hierarchy depend on the permissions that are added to a group).
To make it more clear here you can see a picture of the concept:
So I think the main problems are:
1) How to inherit Groups to create custom groups.
2) How to map the permissions of a model to a group.
3) How groups can be restricted to a CompanyID.
I hope the problem is well defined. Let me know if I have to clarify something.
Thanks in advance for the support.
Edit 1)
For the point 3 I found this answer on SO: Extend django Groups and Permissions but the problem then is how to query for those data and how to check the permissions. And how could you override the save() method to add meta information to the property 'name'? The group name could be something like: "company_id#admin" or "company_id#manager".