简体   繁体   中英

Django: Add additional fields to UserCreationForm

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.

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

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.

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM