I've been having an issue with setting the ForeignKey in one of my model fields for the author variable. See below:
class BugTracker(models.Model):
project_number= models.IntegerField(primary_key=True)
assignee= models.ForeignKey(Developer, on_delete=models.CASCADE)
priority = models.CharField(max_length=10, choices=priority_choices)
summary=models.TextField()
status= models.CharField(max_length=20, choices=progress)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
created_at=models.DateTimeField(default=timezone.now)
updated_at=models.DateTimeField(auto_now=True)
def __str__(self):
return self.summary
def get_absolute_url(self):
return reverse("bug_list")
"IntegrityError at /projects/create/
NOT NULL constraint failed: core_bugtracker.author_id
Request Method: POST
Request URL: http://127.0.0.1:8000/projects/create/
Django Version: 4.1.5
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: core_bugtracker.author_id"
As soon as I add "null=True" to the ForeignKey Field, it works and I don't get an error, but the template shows my variable ({bug.author}} equal to "None" regardless of who I'm signed in as. I tried deleting my database and migration files multiple times, but it still doesn't work.
CodePudding user response:
If you are not passing "author" as a field while saving BugTracker model, you'll get ({bug.author}} as None, because you have set "null=True" in the "author" field declaration - This means you can save BugTracker model without passing an 'author' field and it defaults to null/None.
If you want to set/add an author object to bug_tracker_object, you can do the following. (Note: bug_tracker_object is the BugTracker object that you've populated using fields such as project_number, assignee, priority etc.)
author_object = Author.objects.get(id=<your_author_id>)
bug_tracker_object.author_object = author_object
bug_tracker_object.save()