我正在建立一个django应用程序,其中当我从后端添加学生详细信息时使用一对一的字段,效果很好,但形成了前端形式,它给出以下错误“ / prog中的IntegrityError 唯一约束失败:grading_program_of_study.student_id “
//////////////my view code////////////////
def prog(request):
if request.method == 'POST':
if request.POST['program_name'] and request.POST['date_of_entry'] and request.POST['faculty']and request.POST['department'] and request.POST['program_type'] and request.POST['date_of_complition']:
Program_of_study = program_of_study()
Program_of_study.program_name = request.POST['program_name']
Program_of_study.date_of_entry = request.POST['date_of_entry']
Program_of_study.faculty = request.POST['faculty']
Program_of_study.department = request.POST['department']
Program_of_study.department = request.POST['program_type']
Program_of_study.date_of_complition = request.POST['date_of_complition']
Program_of_study.save()
return redirect('home',{'sucess':'Program added sucessfully'})
else:
return render(request,'grading/home.html')
else:
return render(request,'grading/home.html')
########### my model code################################
class program_of_study(models.Model):
student = models.OneToOneField(student_details, on_delete=models.CASCADE,default = 1)
program_name = models.CharField(max_length=50)
date_of_entry = models.DateField()
faculty = models.CharField(max_length=50)
department = models.CharField(max_length=50)
program_type = models.CharField(max_length=50)
date_of_complition = models.DateField()
def __str__(self):
return self.program_name
答案 0 :(得分:1)
您的问题是学生字段中的默认值。由于您具有OneToOne关系,因此您无法重复值,因此就无法使用默认值。
student = models.OneToOneField(student_details, on_delete=models.CASCADE, default = 1)
您可以解决的问题是将字段类型更改为ForeignKey或删除默认值。
答案 1 :(得分:0)
感谢上帝,我仅用一行代码就解决了这个问题,错误是我试图将数据保存为字符串而不是整数
###############问题的解决方案Program_of_study.student = student_details.object.latest(id)