django.db.utils.OperationalError: table "blog_post" already exists

Question:

I’m creating a blog using Django and anytime I run manage.py migrate, I get the error below:

(venv) (C:UsersKOLAPOAnaconda3) C:ProgrammingWebsitesshelteratyourcrossroadsshelteratyourcrossroads>manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sessions, sites, taggit
Running migrations:
  Applying blog.0001_initial...Traceback (most recent call last):
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbbackendsutils.py", line 62, in execute
    return self.cursor.execute(sql)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbbackendssqlite3base.py", line 335, in execute
    return Database.Cursor.execute(self, query)
sqlite3.OperationalError: table "blog_post" already exists

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:ProgrammingWebsitesshelteratyourcrossroadsshelteratyourcrossroadsmanage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangocoremanagement__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangocoremanagement__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangocoremanagementbase.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangocoremanagementbase.py", line 345, in execute
    output = self.handle(*args, **options)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangocoremanagementcommandsmigrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbmigrationsexecutor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbmigrationsexecutor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbmigrationsexecutor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbmigrationsmigration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbmigrationsoperationsmodels.py", line 96, in database_forwards
    schema_editor.create_model(model)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbbackendsbaseschema.py", line 295, in create_model
    self.execute(sql, params or None)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbbackendsbaseschema.py", line 112, in execute
    cursor.execute(sql, params)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbbackendsutils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbbackendsutils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbutils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangoutilssix.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbbackendsutils.py", line 62, in execute
    return self.cursor.execute(sql)
  File "C:ProgrammingWebsitesshelteratyourcrossroadsvenvlibsite-packagesdjangodbbackendssqlite3base.py", line 335, in execute
    return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: table "blog_post" already exists

Here’s everything in my models.py file:

from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from taggit.managers import TaggableManager
from ckeditor_uploader.fields import RichTextUploadingField

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager, 
            self).get_queryset().filter(status='published')

class Post(models.Model):
    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )
    title = models.CharField(max_length=250)
    subtitle = models.TextField()
    slug = models.SlugField(max_length=250, unique_for_date='publish')
    author = models.ForeignKey(User, related_name='blog_posts')
    image = models.ImageField(upload_to='posts/%Y/%m/%d', blank=True)
    # body = models.TextField()
    body = RichTextUploadingField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    tags = TaggableManager()
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')

    class Meta:
        ordering = ('-publish',)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post_detail', args=[
            self.publish.year, self.publish.strftime('%m'),
            self.publish.strftime('%d'), self.slug])

    objects = models.Manager() # default manager
    published = PublishedManager() # custom manager

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    image = models.ImageField(upload_to='users/%Y/%m/%d', null=True, blank=True)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

    def __str__(self):
        return 'Profile for user {}'.format(self.user.username)

class Feedback(models.Model):
    name = models.CharField(max_length=200, help_text="name of sender")
    email = models.EmailField(max_length=200)
    subject = models.CharField(max_length=200)
    message = models.TextField()
    date = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = "Feedback"

    def __str__(self):
        return (self.name, "-", self.email)

I’m stuck on that error. How do I fix it please?

Asked By: Caspian

||

Answers:

Maybe faking the initial migration of blog app will help you. Try the following.

./manage.py migrate --fake blog 0001_initial

Answered By: Krishna G Nair

Django 3.2

The following worked for me:
delete all the migration files, including the initial migration. Then perform:

python manage.py makemigrations
python manage.py migrate
Answered By: mm_

Every time I see this kind of question I wondered: if the model.py is ok, why does no one suggests (in the answer) dropping the wrong table and – instead – almost everybody suggests deleting all migration files? It’s overkill!

If model.py is proper and ok now, then you can always do two things:

  1. Edit migration files – instead of deleting them. If this doesn’t work, then:
  2. With SQL shell: drop a single (wrong) table by accessing it via SQLite or PostgreSQL – depending on the one that you are using. Also, you can edit and update it.

Update:

There are some cases when things get more tricky. If the problem is related to the foreign key that was added to the particular table in SQLite, then it’s more difficult to solve the problem, than having the same issue but with PostgreSQL. The SQLite is lacking some very handy features like removing a column that has foreign keys. I had a few situations where the first error was related to some table that I needed to drop, but after that, another issue was with a foreign key. Because both problems were related to some model that had a one-to-many relation. That’s why I recommend getting familiar with PostgreSQL. That will make it easier to solve this kind of situation without deleting a whole database.

Answered By: Paweł Pedryc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.