I encountered an issue while migrating a DB using django:
Traceback (most recent call last): File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "myBlog_category" does not exist LINE 1: ...g_category"."name", "myBlog_category"."name" FROM "myBlog_ca... ^
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 975, in _find_and_load_unlocked File "", line 671, in _load_unlocked
File "", line 783, in exec_module File "", line 219, in call_with_frames_removed File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\blog\urls.py", line 8, in path('', include('myBlog.urls')), File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 975, in _find_and_load_unlocked File "", line 671, in _load_unlocked
File "", line 783, in exec_module File "", line 219, in _call_with_frames_removed File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\urls.py", line 2, in from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, AddCategoryView, CategoryView, CategoryListView, LikeView, AddCommentView File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\views.py", line 4, in from .forms import PostForm, EditForm, CommentForm File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\forms.py", line 6, in for item in choices: File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 287, in iter self._fetch_all() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 1303, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 142, in iter return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1108, in results_iter results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql cursor.execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "myBlog_category" does not exist LINE 1: ...g_category"."name", "myBlog_category"."name" FROM "myBlog_ca...
I deployed the app to heroku and got errors so I tried to change the sqlite db to psql before commiting it to heroku but after doing this tutorial migrations did not work anymore, I got stuck on the 3rd step of the tutorial.
I tried the following:
- Delete migrations folder from myBlog
- Delete db.sqlite3 file
- After removing the files/folders above I tried python manage.py makemigrations and got the following error:
Traceback (most recent call last): File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "myBlog_category" does not exist LINE 1: ...g_category"."name", "myBlog_category"."name" FROM "myBlog_ca... ^
The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py",line 401, in execute_from_command_line utility.execute() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 975, in _find_and_load_unlocked File "", line 671, in _load_unlocked File "", line 783, in exec_module File "", line 219, in call_with_frames_removed File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\blog\urls.py", line 8, in path('', include('myBlog.urls')), File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 975, in _find_and_load_unlocked File "", line 671, in _load_unlocked File "", line 783, in exec_module File "", line 219, in _call_with_frames_removed File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\urls.py", line 2, in from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, AddCategoryView, CategoryView, CategoryListView, LikeView, AddCommentView File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\views.py", line 4, in from .forms import PostForm, EditForm, CommentForm File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\forms.py", line 6, in for item in choices: File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 287, in iter self._fetch_all() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 1303, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 142, in iter return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1108, in results_iter results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql cursor.execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "myBlog_category" does not exist LINE 1: ...g_category"."name", "myBlog_category"."name" FROM "myBlog_ca...
- Trying to run the server locally now, doesn't work.
While deploying it to heroku I got ProgrammingError - something close to what I get now. I tried to run:
heroku run python manage.py migrate
But got the app would return me the same error as the same traceback at the begging of the post.
My settings.py file:
"""
Django settings for blog project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
import django_heroku
import dj_database_url
from decouple import config
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-97gr5qi*888x%%n!=yp(uf*xz!8(jucnfd!ln+_zkyg@8#e5th'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myBlog',
'members',
'ckeditor',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware'
]
ROOT_URLCONF = 'blog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.postgresql_psycopg2',
'NAME' : 'my_db',
'USER' : 'hero',
'PASSWORD' : 'my_db @ 123',
'HOST' : 'localhost',
'PORT' : '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
django_heroku.settings(locals())
For any other additional required informations please let me know.
Edit 1: My models.py
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self) :
return self.name
def get_absolute_url(self) :
return reverse('home')
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
bio = models.TextField()
profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile")
website_url = models.CharField(max_length=255, null=True, blank=True)
facebook_url = models.CharField(max_length=255, null=True, blank=True)
instagram_url = models.CharField(max_length=255, null=True, blank=True)
twitter_url = models.CharField(max_length=255, null=True, blank=True)
pinterest_url = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return str(self.user)
def get_absolute_url(self) :
return reverse('home')
class Post(models.Model):
title = models.CharField(max_length=255)
header_image = models.ImageField(null=True, blank=True, upload_to="images/")
title_tag = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default='uncategorized')
snippet = models.CharField(max_length=255)
likes = models.ManyToManyField(User, related_name='blog_posts')
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + ' | ' + str(self.author)
# Create your models here.
def get_absolute_url(self):
return reverse('article-detail', args=(str(self.id),))
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
name = models.CharField(max_length=255)
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
views.py for myBlog app:
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post, Category, Comment
from .forms import PostForm, EditForm, CommentForm
from django.urls import reverse_lazy, reverse
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator
# Create your views here.
def LikeView(request, pk):
post = Post.objects.get(id=pk)
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
liked = False
else:
post.likes.add(request.user)
liked = True
return HttpResponseRedirect(reverse('article-detail', args=[str(pk)]))
class HomeView(ListView):
model = Post
template_name = 'home.html'
ordering = ['-post_date']
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(HomeView, self).get_context_data(*args, **kwargs)
context["cat_menu"] = cat_menu
return context
class ArticleDetailView(DetailView):
model = Post
template_name = 'article_details.html'
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(ArticleDetailView, self).get_context_data(*args, **kwargs)
stuff = get_object_or_404(Post, id=self.kwargs['pk'])
liked = False
if stuff.likes.filter(id=self.request.user.id).exists():
liked = True
total_likes = stuff.total_likes()
context["cat_menu"] = cat_menu
context["total_likes"] = total_likes
context["liked"] = liked
return context
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
def CategoryListView(request):
cat_menu_list = Category.objects.all()
return render(request, 'category_list.html', {'cat_menu_list': cat_menu_list})
def CategoryView(request, cats):
category_posts = Post.objects.filter(category=cats.title().replace('-', ' '))
return render(request, 'categories.html', {'cats': cats.title().replace('-', ' '), 'category_posts': category_posts})
class AddCategoryView(CreateView):
model = Category
fields = '__all__'
template_name = 'add_category.html'
class UpdatePostView(UpdateView):
model = Post
template_name = 'update_post.html'
form_class = EditForm
class DeletePostView(DeleteView):
model = Post
template_name = 'delete_post.html'
success_url = reverse_lazy('home')
class AddCommentView(CreateView):
model = Comment
form_class = CommentForm
template_name = 'add_comment.html'
def form_valid(self, form):
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)
success_url = reverse_lazy('home')