[Django]-How to assign GROUP to user from a registration form (for user) in Django?

15👍

Typically you would pull in the group model from django. Then query the model for the group you would like to add the user. Here is how to below.

from django.contrib.auth.models import Group

def UserRegister(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            group = Group.objects.get(name='group_name')
            user.groups.add(group)
            return redirect('login')
    else:
        form = UserCreationForm()
    return render(request, 'register/user_register.html', {'form': form})

Leave a comment