Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a user to a group at signup using django-userena?

I would like to separate users into two different groups, employer or employee, at signup. I'm using django-userena and for the employer group I'm thinking of using a clone of the same signup view except with a different url tied to it.

So whoever signs up at url(r'^signup/employer/$) will be added to the employer group with

new user = user.groups.add(Group.objects.get(name=employer))

added to the view. Is this the right approach?

like image 613
Jesramz Avatar asked Jan 20 '12 23:01

Jesramz


1 Answers

Edited: form.save() returns the user just created. You have then to simply add it to your group. Your view should look something like:

form = signup_form() 
if request.method == 'POST': 
    form = signup_form(request.POST, request.FILES) 
    if form.is_valid(): 
        user = form.save()
        user.groups.add(Group.objects.get(name='employer'))

I would also consider using signals, if what you want to do is to add every user to your employer group. Something like this will add each newly created user to it, and will allow you to use the default signup view from userena:

# somewhere, in your models.py file
@receiver(post_save, sender=User, dispatch_uid='myproject.myapp.models.user_post_save_handler')
def user_post_save(sender, instance, created, **kwargs):
    """ This method is executed whenever an user object is saved                                                                                     
    """
    if created:
        instance.groups.add(Group.objects.get(name='employer'))
like image 94
StefanoP Avatar answered Nov 15 '22 11:11

StefanoP