UNIQUE 约束失败:auth_user.username 使用自定义设计的表单创建用户时

UNIQUE constraint failed: auth_user.username while creating the user using a custom designed form

我是 django 的新手,我正在为考试门户网站做学生登录。在我看来,我基本上传递了两种形式。一种形式用于获取用户详细信息,第二种形式用于存储学生的详细信息。 我已经使用 django 小部件调整包来加载我的表单字段。我的用户已创建,但同时我仍然收到错误 - UNIQUE constraint failed: auth_user.username.

这是我的 model.py

class StudentInfo(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    mobile = models.IntegerField(max_length=20, blank=True)
    branch = models.CharField(max_length=50, blank=True)

forms.py

class StudentForm(forms.ModelForm)
    class Meta():
        model = User
        fields = ['username', 'email', 'password']
        widgets = {
        'password': forms.PasswordInput()
        }

class StudentInfoForm(forms.ModelForm):
    class Meta():
        model = StudentInfo
        fields = ['mobile','branch']

views.py

def register(request):
    userForm= forms.StudentForm()
    studentForm=forms.StudentInfoForm()
    mydict={'userForm':userForm,'studentForm':studentForm}
    if request.method=='POST':
        userForm=forms.StudentForm(request.POST)
        studentForm=forms.StudentInfoForm(request.POST)
        if userForm.is_valid() and studentForm.is_valid():
            user=userForm.save()
            user.is_active = True
            user.set_password(user.password)
            messages.success(request,"Student User created Succesfully.")

            student=studentForm.save(commit=False)
            student.user=user
            student.save()
            
            my_student_group = Group.objects.get_or_create(name='STUDENT')
            my_student_group[0].user_set.add(user)
            return redirect('login')
        
    return render(request,'student_signup.html',context=mydict)

html 文件

{% load widget_tweaks %}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <title>Student Signup</title>
  </head>
  <body>
    <h1 style="text-align: center; margin-top: 5px;">Student Signup</h1>
    <div class="container mt-5" style="width: 50%;">

    <form method="post">
        {% csrf_token %}
        <div class="mb-3">
          <label for="username" class="form-label">Username</label>
          {
          {% render_field userForm.username type="text" class="form-control" %}

          
        </div>
        <div class="mb-3">
          <label for="password" class="form-label">Password</label>
          
          {% render_field userForm.password type="password" class="form-control" %}

        </div>

        <div class="mb-3">
            <label for="email" class="form-label">Email</label>
            
            {% render_field userForm.email type="email" class="form-control" %}
  
        </div>
        <div class="mb-3">
            <label for="branch" class="form-label">Branch</label>
            
            {% render_field studentForm.branch type="text" class="form-control" %}
  
        </div>

        <div class="mb-3">
            <label for="mobile" class="form-label">Mobile</label>
             
            {% render_field studentForm.mobile type="number" class="form-control" %}
  
        </div>


        
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>

</div>

    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

    
  </body>
</html>

我在 Internet 上搜索,发现当我们保存表单两次时会发生这种情况,但我不认为我在做 so.I 我只调用了一次保存方法。

我认为发生这种情况是因为您的用户实例绑定到表单而不是模型实例本身,然后您将其分配给学生实例

试试看:

def register(request):
    userForm= forms.StudentForm()
    studentForm=forms.StudentInfoForm()
    mydict={'userForm':userForm,'studentForm':studentForm}
    if request.method=='POST':
        userForm=forms.StudentForm(request.POST)
        studentForm=forms.StudentInfoForm(request.POST)
        if userForm.is_valid() and studentForm.is_valid():
            user=userForm.save()
            user.is_active = True
            user.set_password(user.password)
            messages.success(request,"Student User created Succesfully.")

            student=studentForm.save(commit=False)
            student.user=user.instance  # user is bound to the form instance not the model instance
            student.save()
            
            my_student_group = Group.objects.get_or_create(name='STUDENT')
            my_student_group[0].user_set.add(user)
            return redirect('login')
    return render(request,'student_signup.html',context=mydict)