使用Django表单创建注册表单时,如何添加自定义字段?

时间:2019-11-19 21:58:13

标签: python django django-models web-applications django-forms

我是Django的初学者,并且总体来说只是Python,但是我试图创建一个相对简单的Web应用程序,似乎遇到了一些障碍。

我想向我的Django UserCreationForm添加自定义字段,例如名字,姓氏,电子邮件和ID号吗?我应该创建一个单独的Profile模型,如果是的话我该怎么做,还是有其他方法可以实现?

就像我说的,我是一个初学者,所以我将尽可能多地欣赏细节!

1 个答案:

答案 0 :(得分:0)

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

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}