'insert or update on table "django_admin_log" violates foreign key constraint
Trying to save a post on a django project I got this error
The above exception (insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(1) is not present in table "auth_user". ) was the direct cause of the following exception:
The model:
from django.conf import settings
class Tag(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
author = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
content = models.TextField()
image = models.ImageField(upload_to='', blank=True, null=True)
tags = models.ManyToManyField(Tag, blank=True)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
The view:
from django.views.generic import ListView, DetailView
from django.shortcuts import get_object_or_404
from .models import Post
class BlogView(ListView):
template_name = 'base/blog.html'
queryset = Post.objects.all()
paginate_by = 2
class PostView(DetailView):
model = Post
template_name = 'base/post.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
pk = self.kwargs['pk']
slug = self.kwargs['slug']
post = get_object_or_404(Post, pk=pk, slug=slug)
context['post'] = post
return context
How can I solve this problem?
Solution 1:[1]
That because the django_admin_log table still contains a foreign key relation to the old auth_user table.
You need to drop this and recreate the table.
psql => DROP table django_admin_log;
For Django >= 1.7
./manage.py sqlmigrate admin 0001 | ./manage.py dbshell
And that's it :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tanmay Thole |