Showing invalid foreign key django

I am getting this invalid foreign key error in calendars, not sure how to fix it.

Here is the code in my models:

class Calendar(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    start_date = models.DateField()
    end_date = models.DateField()
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)


I am trying to link it to the logged in user, but I don't think it is working. I also tried to print the entries in django shell, but it also gives an error of "NameError: name 'Calendar' is not defined" with this query:

calendars = calendars.objects.all()

What is wrong?

It seems like you have an invalid Calendar record in your database.

Based on the definition of the owner field, it should store the ID of a User record that is the owner of this Calendar.

However, looking at your error message:

The row in table 'calendars_calendar' with primary key '1' has an invalid foreign key: calendar_calendar.owner_id contains a value 'owner id' that does not have a corresponding value in auth_user.id.

This suggests that your calendars_calendar table has a record like this:

| id | owner_id |
|----|----------|
| 1  | owner id |

This is not valid since the value of the owner_id column should be the primary key of a record in the auth_user table.

Why did this happen?/How to fix it?

This invalid record might have entered your database because you used a raw SQL query or a change in model definition. Nonetheless, you have to fix this for this record to work.

If you know the ID of the User that should be the owner of this Calender, you can set it using this query:

Calender.objects.filter(id=1).update(owner_id=<USER_ID_OF_OWNER>)

Why didn't your query work?

NameError: name 'Calendar' is not defined suggests that you are referencing the Calender class where it is not defined. Perhaps you forgot to import it?

Tips

Usually, including the error text for errors like this (that are textual) in your question is easier to use than linking an image.

Back to Top