1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Django: Adding user to groups in a signal

Discussão em 'Python' iniciado por Stack, Outubro 1, 2024 às 08:22.

  1. Stack

    Stack Membro Participativo

    I created a signal which is supped to do 3 things:

    1. Create a User
    2. Create the Profile of said user
    3. Add User to a Group

    Using a signal, steps 1 and 2 work fine but I can't seem to add the user to a group (step 3).

    # Signals
    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
    if created:
    Profile.objects.create(user=instance)
    group = Group.objects.get(name='generics')
    instance.groups.add(group)


    Did some debugging and found out that even if I comment out Profile.objects.create(user=instance) I still can't add any groups to instance.

    Am I missing anything here? I'm not getting any errors.

    Edit 1: This is a custom User model.

    from django.contrib.auth.models import AbstractUser

    class User(AbstractUser):
    first_name = None
    last_name = None

    class Meta:
    verbose_name_plural = 'users'

    def __str__(self):
    return self.username


    I simply moved first_name and last_name to the Profile table. Didn't do anything else as you can see. Users and Profiles are successfully being created so this custom model works just fine.

    Although unnecessary, I added instance.save() after adding the group but it still won't work. The admin shows no groups have been added and the the db table core_user_groups is still empty.

    Edit 2: Add console test

    Even more weird, I tried adding the group using ./manage.py shell and it works fine.

    >>> from core.models import User
    >>> from django.contrib.auth.models import Group
    >>> group = Group.objects.get(pk=1)
    >>> group
    <Group: generics>
    >>> user = User.objects.get(pk=23)
    >>> user
    <User: sonic>
    >>> user.groups.add(group)

    # At this point I check the admin and the db and it worked. Hmmm....but how to do it within a signal...

    Continue reading...

Compartilhe esta Página