首页 > 解决方案 > 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!

标签: pythondjangodjango-modelsweb-applicationsdjango-forms

解决方案


对于名字、姓氏和电子邮件字段,您无需执行任何操作。但是对于ID我建议你创建一个单独的模型,这实际上很简单!

模型.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)

表格.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!')

视图.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}

推荐阅读