1
votes

can i add fields like address,city,state,country,pincode and security question and answer to the extension of UserCreationForm that currently contains username,email,password1 and password2. if yes then please illustrate how?

forms.py

class UserCreationForm(UserCreationForm):
    email = EmailField(label=_("Email address"), required=True,
        help_text=_("Required."))
    city= forms.CharField(label= _("City"),max_length=20, required=True)
    state= forms.CharField(label= _("State"),max_length=20, required=True)

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2","city","state")

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        user.city = self.cleaned_data["city"]
        user.state = self.cleaned_data["state"]

        if commit:
            user.save()
        return user
2

2 Answers

1
votes

currently you are extending UserCreationForm class if you have other fields in user model then you can use forms.ModelForm and just mention other fields.

for example

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username','name', 'email', 'phone', 
              'address','city','state', 'first_time']

if you want to use custom form then.

class UserForm(forms.Form):
      name = forms.CharField(label= _("Name"))
      address = forms.CharField(label=_("Address"))
      etc.
2
votes

Yes just do like you did with email:

class UserCreationForm:
    a_field = WhateverField(whatever='whatever'...)

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")

The field is now added in your form.