Search code examples
pythondjangodjango-registration

How to add extra fields to django registration form?


I have a registration form which generates in view. Now I need to add some fields from other model. How should I change view to add fields from another model?

Here is my view code:

def register(request):
    """ User registration """
    if auth.get_user(request).username:
        return redirect('/')

    context = {}
    context.update(csrf(request))
    context['form'] = UserCreationForm()
    if request.POST:
        newuser_form = UserCreationForm(request.POST)
        if newuser_form.is_valid():
            newuser_form.save()
            newuser = auth.authenticate(username=newuser_form.cleaned_data['username'],
                                    password=newuser_form.cleaned_data['password2'])
        auth.login(request, newuser)
        return redirect('/')
        else:
            context['form'] = newuser_form

    return render(request, 'user_auth/user_auth_register.html', context)

Solution

  • Something like this should help you:

    from django import forms
    from django.contrib.auth.models import User
    from django.contrib.auth.forms import UserCreationForm
    
    class UserCreateForm(UserCreationForm):
        extra_field = forms.CharField(required=True)
    
        class Meta:
            model = User
            fields = ("username", "extra_field", "password1", "password2")
    
        def save(self, commit=True):
            user = super(UserCreateForm, self).save(commit=False)
            user.extra_field = self.cleaned_data["extra_field"]
            if commit:
                user.save()
            return user
    

    Basically, extending UserCreationForm and adding an extra field. Also, save it in the save() method.

    Hope it helps.