简体   繁体   中英

How can I add custom fields when creating a sign up form using Django form?

I am very much a beginner to Django and just Python overall, but I am trying to create a relatively simple web app and I seem to be running into some obstacles.

I would like to add custom fields to my Django UserCreationForm like first name, last name, email and ID number? Should I create a separate Profile model and if so how should I do that, or is there some other way to achieve this?

Like I said, I am a beginner so I would appreciate as much detail as possible!

For first name, last name and email fields you won't need to do anything. But for ID I suggest you create a separate model, that's really simple actually!

models.py

from django.contrib.auth.models import User

class IdNumber(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    id_number = models.TextField(max_length=9)

forms.py

from django.contrib.auth.models import User 

class SignUpForm(forms.ModelForm):
    id_number = forms.CharField(max_length=9, required=True)
    password = forms.CharField(max_length=15, required=True)
    password_confirm = forms.CharField(max_length=15, required=True)

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', 'username', 'password']

        def clean(self):
            cleaned_data = super(SignUpForm, self).clean()
            password = cleaned_data.get('password')
            password_confirm = cleaned_data.get('password_confirm')

            if password != password_confirm:
                raise forms.ValidationError('Passwords do not match!')

views.py

from .models import IdNumber
from .forms import SignUpForm

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            id_number = form.cleaned_data['id_number']

            user.set_password(password)

            id_model = IdNumber(user.id)
            id_model.user = user
            id_model.id_number = id_number

            id_model.save()
            form.save()

            return HttpResponseRedirect('some_url')

        else:
            return render(request, 'your_app/your_template.html', {'form': form})

    else:
        form = SignUpForm()

    return render(request, 'your_app/your_template.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