1

Currently, I am facing the above-mentioned error when I am trying to execute the command

python3 manage.py migrate

I cannot figure out the issue and the posts on Stackoverflow suggest to delete the migrations and recreate it, which I did. But I still face the same issue.

Please find below some code:

models.py:

from __future__ import unicode_literals
from django.db import models
from bokeh.themes import default
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import AbstractUser
from django.utils import timezone

# Create your models here.
class Project(models.Model):
    REQUEST_STATUS = (
        ('Pending', 'Pending'),
        ('Approved', 'Approved'),
        ('Denied', 'Denied'),
    )

    form_type = models.CharField(max_length=20, blank=False, null=False)
    created_at = models.DateTimeField(default=timezone.now())
    status = models.CharField(max_length=20, choices=REQUEST_STATUS, default='Pending')
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.id)

class Profile(models.Model):
    NORMAL = 1
    APPROVER = 2
    REVIEWER = 3
    ROLE_CHOICES = (
        (NORMAL, 'Normal'),
        (APPROVER, 'Approver'),
        (REVIEWER, 'Reviewer'),
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True)   
    def __str__(self):  # __unicode__ for Python 2
        return self.user.username


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

admin.py:

from django.contrib import admin

# Register your models here.
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

from .models import Profile, Project

admin.AdminSite.site_url = '/MyProject'
class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Sites'
    fk_name = 'user'


class CustomUserAdmin(UserAdmin):
    inlines = (ProfileInline, )
    list_display = ('id', 'username', 'email', 'first_name', 'last_name', 'is_staff', 'get_role')
    list_select_related = ('profile', )

    def get_role(self, instance):
        return instance.profile.role
    get_role.short_description = 'Role'

    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(CustomUserAdmin, self).get_inline_instances(request, obj)


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

admin.site.register(Project)

urls.py:

from django.contrib import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('APP.urls')),
    re_path(r'^APP/admin/', admin.site.urls, name='admin'),
    re_path(r'^logoutview/admin/', admin.site.urls, name='admin'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

settings.py:

....
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    #'default': {
        #'ENGINE': 'django.db.backends.sqlite3',
        #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    #}
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'app_db',
        'HOST': '/Applications/djangostack-2.0.2-3/postgresql',
        'PORT': '5432',
        'USER': 'app_user',
       'PASSWORD': '**********'
    }
}
....

Here's my traceback:

File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: column "role" does not exist
LINE 1: ...l_profile" ALTER COLUMN "role" TYPE integer USING "role"::in...
                                                             ^


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

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/core/management/commands/migrate.py", line 200, in handle
    fake_initial=fake_initial,
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/migrations/migration.py", line 122, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/migrations/operations/fields.py", line 216, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/base/schema.py", line 509, in alter_field
    old_db_params, new_db_params, strict)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/postgresql/schema.py", line 122, in _alter_field
    new_db_params, strict,
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/base/schema.py", line 650, in _alter_field
    params,
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/base/schema.py", line 117, in execute
    cursor.execute(sql, params)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "role" does not exist
LINE 1: ...l_profile" ALTER COLUMN "role" TYPE integer USING "role"::in...
                                                            ^

Any help or advice will be appreciated! I will be more than happy to provide any further code or information needed. Thanks in advance for all the support and help.

Regards,

Amey Kelekar

3 Answers 3

4

First login to postgres database and select app_db Then delete the row from django_migrations which is related to role column.

Then run makemigrations and migrate command respectively.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your answer. I just went a step ahead and deleted the table Profile instead of deleting the column role. But I believe your solution is sufficient enough to resolve my issue.
4

You may be having the same error persisting and several unapplied migrations under the same app. In that case do;

yourApp$./manage.py makemigrations
yourApp$./manage.py showmigrations
# delete unapplied migrations indicated by empty [] before name of the file
yourApp$./manage.py migrate --fake

After doing this the app may look to be working but still the column may not exist in the database. You may realize this when you try to do a POST to the db. If the error arises again, delete the migration involved with role field both from migrations folder in the code and from django_migrations table in the database, then do migrations->migrate

yourComp$sudo -u postgres psql
postgres=#\c yourdb_name;
your_db=#select * from django_migrations;
# identify the id of the migration affecting 'role' column
your_db=#delete from django_migrations where id=3;
your_db=#delete from django_migrations where id=4;

Delete the same migrations from the code and do;

 (venv)yourApp$./manage.py makemigrations appname
 (venv)youApp$./manage.py migrate appname

1 Comment

Every now and again, I get a 'stuck' migration that Django doesn't pick up. Some combination of 1) faking the migrations, and 2) deleting/recreating the field always gets things going again.
-1

In my own case, I had to restart the Django app and run migrations again. I think it was because I updated my Django model.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.