1
votes

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.

2
# This Link To Stackoverflow Will answer your questionHamBurger
This Link stackoverflow.com/questions/48049498/… Will answer your questionHamBurger

2 Answers

1
votes

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',)
1
votes

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.