Search code examples
pythondjangodjango-usersdjango-custom-user

Add user to a group at signup in Django


New to Django here. There are three types of users: Bronze, Silver and Gold with different permissions. All users start out as Bronze when they sign up and then move upwards when they fulfill certain conditions. Therefore I tried to customize the User model using Django's tutorial. So far I have been able to create the users correctly. However, I want to now add these users to the Bronze group as soon as they sign up and am not sure where do I put that code. Here is my code. Its fairly straightforward. models.py

# models.py
from django.contrib.auth.models import AbstractUser, Group
from django.db import models

class CustomUser(AbstractUser):
    pass
    # add additional fields in here

    def __str__(self):
        return self.username

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):

    class Meta:
        model = CustomUser
        fields = ('username', 'email')

class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = CustomUser
        fields = ('username', 'email')

views.py

from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView
from .forms import CustomUserCreationForm

# Create your views here.
class SignUpView(CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'

admin.py

from django.contrib import admin

# Register your models here.
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin

from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['email', 'username',]

admin.site.register(CustomUser, CustomUserAdmin)

I can manually add the user to the group on django shell just fine.

>>>currUser.groups.add(Group.objects.get(name='Bronze'))

Where does this code go in, so that this command is executed at the time of signup?

Any help is appreciated.

Thanks


Solution

  • def signup(request):

    if request.method == 'POST':
        form = RegistrationForm(request.POST)
    
        if form.is_valid():
            user = form.save(commit=False)
    
            user.save()
    
            user_group = Group.objects.get(name='Mygroup') 
    
            user.groups.add(user_group)
    
            #log the user in
            login(request, user)
    
            return redirect('/summury')
    
    else:
    
        form = RegistrationForm()
    
    return render(request, 'account/pages/register.html', {'form':form})