djangodjango-allauth

Django Allauth: How to add more custom fields on signup form?


So, I'm trying to make a custom signup form while using Django allauth on my project. I've reached their documentation and tried to apply it on my code.

In my forms.py I've put this:

class MyCustomSignupForm(SignupForm):
    cpf_cnpj = forms.CharField(max_length=14)
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)

    def save(self, request):

        # Ensure you call the parent class's save.
        # .save() returns a User object.
        user = super(MyCustomSignupForm, self).save(request)

        # Add your own processing here.
        user.first_name = self.cleaned_data['first_name']
        user.last_name= self.cleanedD_data['last_name']
        user.cpf_cnpj = self.cleaned_data['cpf_cnpj']
        user.save()
        # You must return the original result.
        return user

I've put the ACCOUNT_FORMS = {'signup': 'mysite.forms.MyCustomSignupForm'} in settings.py as required too.

As you can see on the image linked below, it saves to the user their first and last name, but it doesnt save the cpf_cnpj field Value. What should I do to save this to the user?

Admin Panel - Users

Signup Template


Solution

  • in your forms.py add the fields like this to add an extra field in default user creation form provide by django

    from django.contrib.auth.forms import UserCreationForm
    class MyCustomSignupForm(UserCreationForm):
        email = forms.EmailField(max_length=254, required=True, help_text='Required. Inform a valid email address.')
        cpf_cnpj = forms.CharField(max_length=14)
        first_name = forms.CharField(max_length=30)
        last_name = forms.CharField(max_length=30)
    
        class Meta:
            model = User
            fields = ('username', 'email', 'cpf_cnpj', ' first_name', 'last_name', 'password1', 'password2', )
    

    and acc to that change you views.py

    from .forms import *
    
    def register(request):
        if request.method == 'POST':
            form = MyCustomSignupForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect('accounts:login')
        else:
            form = MyCustomSignupForm()
        return render(request, 'register.html', {'form': form})
    

    urls.py

     path('register/',views.register,name='register'),