如何在 Django 中使用 auth_user 模型和自定义模型字段创建自定义注册表单

How to create custom registration form using auth_user model and cutom model fields in django

我是 django 的新手,我有带有额外状态和标题模型的自定义用户模型。到目前为止,我完成了数据库部分,如何为带有外键字段的自定义用户模型创建注册表单。 我的模型 class 代码:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractUser

class Title(models.Model):
value = models.CharField(max_length=100, null=True, blank=True)

class Meta:
    db_table = 'title'

class Status(models.Model): 
value = models.CharField(max_length=100, null=True, blank=True)

class Meta:
    db_table = 'status'

class User(AbstractUser):

filenumber = models.CharField(max_length=9, null=True, blank=True)
personalemail = forms.EmailField(required=True)
intakeyear = models.IntegerField(null=True, blank=True)
title = models.ForeignKey(Title, on_delete=models.CASCADE, null=True, blank=True)
status = models.ForeignKey(Status, on_delete=models.CASCADE, null=True, blank=True)

我的settings.py:

AUTH_USER_MODEL = 'student.User'# changes built-in user model to ours

我如何创建用户注册表单字段,例如 名字、姓氏、职务、状态、电子邮件、个人电子邮件、密码、密码确认。我向用户模型标题和状态(外键字段)和文件号、intakeyear、personalemail 添加了额外的字段

我的form.py文件:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.forms import ModelForm

from student.models import User
from student.models import Title, Statu

class StudentNewRegistrationForm(forms.ModelForm):
title = forms.CharField(required=True)
intakeyear = forms.IntegerField(required=True)
email = forms.EmailField(required=True)
personalemail = forms.EmailField(required=True)
status = forms.CharField(required=True)


def __init__(self, *args, **kwargs):
    super(StudentNewRegistrationForm, self).__init__(*args, **kwargs)
    title = [('', 'Choose a title')]
    title.extend(Title.objects.values_list('id', 'value'))
    self.fields['title'] = forms.ChoiceField(choices=title)

    status = [('', 'Choose a status')]
    status.extend(Status.objects.values_list('id', 'value'))
    self.fields['status'] = forms.ChoiceField(choices=status)

class Meta:
    model = User
    fields = ['username','first_name','last_name','email','password1',
            'password2''title','status','intakeyear','personalemail'
    ]

def save(self, commit=True):
    user = super(StudentNewRegistrationForm, self).save(commit=False)
    user.first_name = self.cleaned_data['first_name']
    user.last_name = self.cleaned_data['last_name']
    user.email = self.cleaned_data['email']
    user.personalemail = self.cleaned_data['email']
    user.title = self.cleaned_data['title']
    user.intakeyear = self.cleaned_data['intakeyear']
    user.status = self.cleaned_data['status']
    user.password1 = self.cleaned_data['password1']
    user.password2 = self.cleaned_data['password2']

    if commit:
        user.save()
    return user

views.py:

from django.shortcuts import render, redirect
from django.urls import reverse
from django.contrib.auth.models import User
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from .forms import StudentNewRegistrationForm

def student_new_registration(request):
  if request.method == 'POST':
    form = StudentNewRegistrationForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect(reverse('student:home'))

else:
    form = StudentNewRegistrationForm()

    args = {'form': form}
    return render(request, 'student/studentnewregistrationform.html', args)

studentnewregistrationform.html:

{% extends 'base.html' %}

{% block head %}
<title>Student Registration&nbsp Form</title>
{% endblock %}

{% block body %}
<div class="container">
<form method="post">
    {% csrf_token %}
    <div class="row">
    <div class="col-sm-4">
         <h3> Student&nbsp;Registration&nbsp;Form</h3>
    </div>
    </div>
    <br>
    <div class="row">
        <div class="col-sm-2">{{ form.title.label }}</div>
        <div class="col-sm-3">{{ form.title }}</div>
        <div class="col-sm-4">{{ form.title.errors }}</div>
    </div>
     <br>
    <div class="row">
        <div class="col-sm-2">{{ form.firstname.label }}</div>
        <div class="col-sm-3">{{ form.firstname }}</div>
        <div class="col-sm-4">{{ form.firstname.errors }}</div>
    </div>
     <br>
    <div class="row">
        <div class="col-sm-2">{{ form.lastname.label }}</div>
        <div class="col-sm-3">{{ form.lastname }}</div>
        <div class="col-sm-4">{{ form.lastname.errors }}</div>
    </div>
    <br>
    <div class="row">
        <div class="col-sm-2">{{ form.email.label }}</div>
        <div class="col-sm-3">{{ form.email }}</div>
        <div class="col-sm-4">{{ form.email.errors }}</div>
    </div>
    <br>
    <div class="row">
        <div class="col-sm-2">{{ form.personalemail.label }}</div>
        <div class="col-sm-3">{{ form.personalemail }}</div>
        <div class="col-sm-4">{{ form.personalemail.errors }}</div>
    </div>
    <br>

    <br>
    <div class="row">
        <div class="col-sm-2">{{ form.intakeyear.label }}</div>
        <div class="col-sm-3">{{ form.intakeyear }}</div>
        <div class="col-sm-4">{{ form.intakeyear.errors }}</div>
    </div>
    <br>

    <div class="row">
        <div class="col-sm-2"><label for="{{ form.password1.label }}">Password</label></div>
        <div class="col-sm-3">{{ form.password1 }}</div>
        <div class="col-sm-4">{{ form.password1.errors }}</div>
    </div>
    <br>
   <div class="row">
        <div class="col-sm-2"><label for="{{ form.password2.id_for_label }}">ConfirmPassword</label></div>
        <div class="col-sm-3">{{ form.password2 }}</div>
        <div class="col-sm-4">{{ form.password2.errors }}</div>
    </div>

    <br><br>
    <div class="row">
        <div class="col-sm-2 col-sm-offset-2"> <input type="submit" name="submit" value="Submit" class="btn btn-primary"/></div>
        <div class="col-sm-2"></div>
    </div>
</form>
</div>
{% endblock %}

我在这里加载了状态和标题模型的数据固定装置,例如下拉列表,我现在不知道哪里做错了我收到错误

ValueError at /student/studentnewregistration/
Cannot assign "'100000002'": "User.title" must be a "Title" instance.

任何人都可以帮助我在此先感谢

因为 titlestatus 模型的字段是 ForeignKyy 你应该使用 ModelChoiceField 而不是 ChoiceField 像这样:

def __init__(self, *args, **kwargs):
    super(StudentNewRegistrationForm, self).__init__(*args, **kwargs)
    self.fields['title'] = forms.ModelChoiceField(queryset=Title.objects.all(), empty_label='Choose a title')

    self.fields['status'] = forms.ModelChoiceField(queryset=Status.objects.all(), empty_label='Choose a status')

要显示值而不是 id,只需将 __str__() 方法添加到 StatusTitle 模型:

class Title(models.Model):
    ...
    def __str__(self):
        return.self.value

class Status(models.Model): 
    ...
    def __str__(self):
        return.self.value