CLG
CLG

Reputation: 43

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

The problem that I face, is that I do not know how to assign a group to a user directly from a formal registration of a template (application) in Django. My user registration view is this:

def UserRegister(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('login')
    else:
        form = UserCreationForm()
    return render(request, 'register/user_register.html', {'form': form})

Upvotes: 3

Views: 9481

Answers (1)

Mitchell Walls
Mitchell Walls

Reputation: 1151

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})

Upvotes: 15

Related Questions