Reputation: 401
I have a model in order to extend the user model with some extra fields. The "therapeut" model has a user field that's a OneToOneField connected to User from django.contrib.auth.models. Here's the code:
from django.db import models
from django.contrib.auth.models import User
class Therapeut(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# some more fields here
Now when I want to add a "therapeut" from the model through the Django Admin, I can choose from the available Users or add a new one.
When click I add a new one (green + next to the User dropdown), I would like that new user to have staff status and add it to the user group "therapeuten", in order to manage the permissions for this new user.
I dont see how to archieve this (automatically), neither do I have the option to set staff status and user group in the popup. Note I am logged in as the superuser. See pic:
Any help on how to do this would be much appreciated!
Upvotes: 2
Views: 969
Reputation: 401
OK so I figured out how to do it, I'm adding the solution here for reference:
Override the save method on the Therapeut class like so:
class Therapeut(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# some more fields here
# override save method to add staff status to connected user and add it to therapeutengroup
def save(self, *args, **kwargs):
userObj = self.user
userObj.is_staff = True
userObj.save()
therapGroup = Group.objects.get(name='therapeut')
therapGroup.user_set.add(userObj)
super(Therapeut, self).save(*args, **kwargs)
However, if someone else has a better or different solution, More than welcome to suggest it here!
Upvotes: 2