2

I am very new to django and I've been battling with this particular project for a while now. I get a not null constraint error every time I try and submit my form(which ultimately creates Visitor and VisitRequests objects). The error comes from this line of code...visit_request = VisitRequests(staff=staff, visitor=visitor, comment=comment, token=token, status=None).save()... Please view the code below.

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()

models.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)
B.obed
  • 107
  • 9

1 Answers1

2

Your implementation is assuming Django's save returns the model object, which is not the case. You may want to read Why does django ORM's save method not return the saved object? for further understanding.

In your case you can use Django's create function to create and get the returned object:

visitor = Visitor.objects.create(visitor_name=visitor_name)
visit_request = VisitRequests.objects.create(staff=staff, visitor=visitor, comment=comment, token=token, status=None)
Aurora Wang
  • 1,822
  • 14
  • 22