gpt4 book ai didi

python - NOT NULL 约束失败 : portal_visitrequests. visitor_id

转载 作者:太空宇宙 更新时间:2023-11-04 04:25:21 25 4
gpt4 key购买 nike

我是 django 的新手,我已经为这个特定项目奋斗了一段时间。每次尝试提交表单(最终创建 Visitor 和 VisitRequests 对象)时,我都会收到一个非空约束错误。错误来自这行代码...visit_request = VisitRequests(staff=staff, visitor=visitor, comment=comment, token=token, status=None).save()... 请查看下面的代码。

views.py

def formpage(request):
if request.method=='POST':
token=secrets.token_urlsafe(20)
visitor_name=request.POST.get('visitorsname')
comment=request.POST.get('comment')
visit_type=request.POST.get('visit_type')
visit_content='You have a waiting visitor'+'\n'+'Name:'+visitor_name+'\n'+'Purpose Of Visit:'+visit_type+'\n'+'Additional Comment:'+comment+'\n'+token
staff_id=request.POST.get('staff')
staff=Staff.objects.get(id=staff_id)
staff_email=staff.staff_email
req_comment = request.POST.get('req_comment')
request_id = (request.POST.get('request_id'))
visitor=Visitor(visitor_name=visitor_name).save()
visit_request = VisitRequests(staff=staff, visitor=visitor, comment=comment, token=token, status=None).save()

模型.py

class Staff(models.Model):
staff_name = models.CharField(max_length=250)
staff_email = models.CharField(max_length=250, default="")

def __str__(self):
return self.staff_name

class Visitor(models.Model):
visitor_name = models.CharField(max_length=250)
timestamp = models.DateTimeField(default=timezone.now)

def __str__(self):
return '{}'.format(self.visitor_name)

class VisitRequests(models.Model):
staff=models.ForeignKey(Staff, on_delete=models.CASCADE)
visitor = models.ForeignKey(Visitor, on_delete=models.CASCADE)
comment= models.TextField(default='')
status= models.NullBooleanField()
token=models.CharField(max_length=20)

最佳答案

您的实现假设 Django 的 save 返回模型对象,但事实并非如此。您可能想阅读 Why does django ORM's save method not return the saved object?以便进一步了解。

在您的情况下,您可以使用 Django's create创建和获取返回对象的函数:

visitor = Visitor.objects.create(visitor_name=visitor_name)
visit_request = VisitRequests.objects.create(staff=staff, visitor=visitor, comment=comment, token=token, status=None)

关于python - NOT NULL 约束失败 : portal_visitrequests. visitor_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53615497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com