Search code examples
pythondjangodjango-modelsdjango-admindjango-users

How to add a user to a ManyToManyField when creating User in Django?


Models.py:

class RegularUser(MyUser):
    MyUser.is_staff = False
    MyUser.is_superuser = False

class Meta:
    verbose_name = 'Usuario Regular'
    verbose_name_plural = 'Usuarios Regulares'



class AdminUser(MyUser):
    usuarios = models.ManyToManyField(RegularUser, help_text="Selecciona los usuarios que administra", blank=True)
    MyUser.is_staff = True

class Meta:
    verbose_name = 'Administrador'
    verbose_name_plural = 'Adminsitradores'

I want the next: I log in the admin site as AdminUser, which have staff permission. Then I can create RegularUsers. When I create a new RegularUser I want link this Regular User to the AdminUser through the ManyToManyField so this RegularUser owns to the AdminUser. And the AdminUser could manage this RegularUser in the adminSite.

I want some like this:

class RegularUserCreationForm(forms.ModelForm): ... ...

@receiver(post_save, sender=RegularUser)
def link_user_admin(sender, instance, created, **kwargs):
    if created:
        instance.adminuser = request.user

But adminuser isn't a field of RegularUser. And using request in signals is forbidden. Can someone help me please?


Solution

  • Well. I have found the solution. I need to use the request in the post_save method. However, you can't use it in Django signals, so it's possible to use the Django save_model method which you can get access to the request.

        def save_model(self, request, obj, form, change):
            if obj:
                # Save the object
                super().save_model(request, obj, form, change)
                # Add the user instance to M2M field of the request.user (The admin User) who create the RegularUser 
                request.user.adminuser.usuarios.add(obj)