2

Can we add additional fields to UserCreationForm in django.

By default there are 5 fields in UserCreationForm:

  1. username
  2. email
  3. first_name
  4. last_name
  5. password

If I want to add additional fields like age, gender then how can I add these in UserCreationForm.

I am new to django any reference or descriptive code will be appreciable.

Akshat Zala
  • 710
  • 1
  • 8
  • 23
L Lawliet
  • 419
  • 1
  • 7
  • 20
  • # This Link [To Stackoverflow](https://stackoverflow.com/questions/48049498/django-usercreationform-custom-fields) Will answer your question – Aryan Aug 06 '20 at 05:39
  • This Link https://stackoverflow.com/questions/48049498/django-usercreationform-custom-fields Will answer your question – Aryan Aug 06 '20 at 05:40

3 Answers3

3

Do This As Per The Link

class SignUpForm(UserCreationForm):
    # My Own Custom Fields
    username = forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'}))
    first_name = forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}), max_length=32, help_text='First name')
    last_name=forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}), max_length=32, help_text='Last name')
    email=forms.EmailField(forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'}), max_length=64, help_text='Enter a valid email address')
    password1=forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}))
    password2=forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password Again'}))

    # The Default Fields Of The UserCreation Form
    class Meta(UserCreationForm.Meta):
        model = User
        # I've tried both of these 'fields' declaration, result is the same
        # fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )
        fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',)
Aryan
  • 1,093
  • 9
  • 22
  • 2
    Thanks for response but the fields you have mentioned are already present in UserCreationForm, I am asking about some extra fields – L Lawliet Aug 06 '20 at 05:45
  • @ShinChan the comment where i wrote "My Own Custom Fields" You Can Always Change the fields as per you requirenents. – Aryan Aug 06 '20 at 05:47
  • Yes I agree with @AryanMishra. You can change the fields accordingly. – Akshat Zala Aug 06 '20 at 07:46
3

There are a few steps we need to follow, step 1 : Inherit the UserCreationForm and add custom form fields to it, as per your case in forms.py

class SignUpForm(UserCreationForm):
    age = forms.IntegerField()
    gender = forms.CharField()

    class Meta:
        model = User
        fields = ['username', 'age', 'gender', 'password1', 'password2']

step 2 : Create a model as per your custom fields and create a OneToOneField relation with User in models.py file

from django.contrib.auth.models import User

class UserData(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    age = models.PositiveIntegerField()
    gender = models.CharField(max_length=20)

step 3 : create a view that will invoke during POST method and will create a new user instance and will store the extra field data to the model which we created

def register_user(request):
    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            age = form.cleaned_data.get('age')
            gender = form.cleaned_data.get('gender')
            user = User.objects.get(username=username)
            user_data = UserData.objects.create(user=user, age=age, gender=gender)
            user_data.save()
            return redirect('home')
    else:
        form = SignUpForm()
    return render(request, 'base/signupform.html', {'form':form})
sagar_v_p
  • 66
  • 3
2

If you wish to store information related to User, you can use a OneToOneField to a model containing the fields for additional information.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    additional_field1 = models.SomeField()
    .....

Read the docs here for the details on extending the user model.

arjun
  • 7,230
  • 4
  • 12
  • 29