我正在尝试实现“学生已连接到用户”,“作业已连接到学生”。
Django迁移问题。
django.db.utils.IntegrityError:唯一约束失败:Student_student.user_id
models.py文件
models.py
from django.db import models
from django.utils import timezone
from django.core.validators import MinLengthValidator,MaxValueValidator
from django.contrib.auth.models import User
# Create your models here.
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,primary_key=True,default=111111)
student_name = models.CharField(max_length = 20)
student_address = models.TextField()
student_bloodgrp = models.CharField(max_length = 3)
#This will be used to upload image of student in some directory not in database
student_image = models.ImageField(upload_to ='profile_pic/')
student_mail = models.EmailField()
student_dob = models.DateTimeField()
student_branch = models.CharField(max_length = 3)
student_reg_no = models.IntegerField(validators=[MaxValueValidator(9999999999)])
student_mob = models.IntegerField(validators=[MaxValueValidator(9999999999)])
student_sem = models.IntegerField(validators=[MaxValueValidator(8)])
student_accom = models.CharField(max_length = 1) # y for boarders & n for non-boarders
class Meta:
verbose_name_plural = "Students"
class Subjects(models.Model):
subjectName = models.CharField(max_length=100,primary_key=True)
branch = models.CharField(max_length=100)
semester = models.IntegerField()
class Meta:
verbose_name_plural = "Subjects"
def __str__(self):
return self.subjectName+"--"+self.branch+"--"+str(self.semester)
class Assignments(models.Model):
student = models.ForeignKey(Student,on_delete=models.DO_NOTHING)
subject = models.ForeignKey(Subjects,on_delete=models.DO_NOTHING)
document = models.FileField(upload_to='assignments/')
class Meta:
verbose_name_plural = "Assignments"
def __str__(self):
return self.student.student_name
forms.py此处
forms.py
from django import forms
from .models import Assignments
class AssignmentForm(forms.ModelForm):
class Meta:
model = Assignments
fields = ('student', 'document','subject' )
******************************************************************
views.py here
views.py
from django.shortcuts import render,redirect
from .forms import AssignmentForm
from django.contrib.auth.decorators import login_required
def mainStudent(request):
return render(request,'Student/main.html')
def masterStudent(request):
return render(request,'Student/master.html')
@login_required
def uploadAssignment(request):
if request.method == 'POST':
form = AssignmentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('student-main')
else:
form =AssignmentForm()
return render(request, 'Student/upload_Assignment.html', {
'form': form
})
我希望将学生用户ID和密码连接到User。 将第一个字段分配为学生。
答案 0 :(得分:0)
您正在为OneToOneField
使用默认值,这实际上没有任何意义。使用OneToOneField
意味着每个Student
只能有一个User
记录。该默认值将在第一次创建Student
而没有User
时起作用,但是下次它将失败,并出现唯一的约束错误。迁移可能正在尝试添加多个Student
记录而没有User
。
您应该删除默认值并检查数据,以了解没有Student
的{{1}}的来源。或者,您可以将User
字段设置为可空并删除user
,以便Django创建一个隐式的primary_key=True
主键:
id