Django Migrating DB django.db.utils.ProgrammingError: relation django_site does not exist

2024/9/20 7:17:51

Doing a site upgrade for Django, now pushing it to the server when I try python manage.py makemigrations I get this error

(kpsga) sammy@kpsga:~/webapps/kpsga$ python manage.py makemigrations
Traceback (most recent call last):
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _executereturn self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "django_site" does not exist
LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si...^The above exception was the direct cause of the following exception:
...File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/sammy/webapps/kpsga/kpsga/urls.py", line 27, in <module>path('blog', include('blog.urls')),
...
File "/home/sammy/webapps/kpsga/blog/urls.py", line 2, in <module>from blog.views import LatestBlogEntries, blog_archive, blog_entry_by_id, blog_entry
File "/home/sammy/webapps/kpsga/blog/views.py", line 10, in <module>class LatestBlogEntries(Feed):
File "/home/sammy/webapps/kpsga/blog/views.py", line 11, in LatestBlogEntriescurrent_site = Site.objects.get_current()
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/contrib/sites/models.py", line 58, in get_currentreturn self._get_site_by_id(site_id)
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/contrib/sites/models.py", line 30, in _get_site_by_idsite = self.get(pk=site_id)
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_methodreturn getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/query.py", line 425, in getnum = len(clone)
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/query.py", line 269, in __len__self._fetch_all()
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/query.py", line 1308, in _fetch_allself._result_cache = list(self._iterable_class(self))
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/query.py", line 53, in __iter__results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1156, in execute_sqlcursor.execute(sql, params)
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in executereturn self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappersreturn executor(sql, params, many, context)
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _executereturn self.cursor.execute(sql, params)
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _executereturn self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "django_site" does not exist
LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si...

though I've got these added to the settings file

INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',#additional django'django.contrib.sites',
]SITE_ID = 1

LatestClass

class LatestBlogEntries(Feed):current_site = Site.objects.get_current()title = current_site.name + " - Latest News"link = "/news/"description = "Latest news and updates from " + current_site.domaindef items(self):return BlogEntry.objects.all()[:10]def item_title(self, item):return item.titledef item_description(self, item):return item.description
Answer

The ProgrammingError is a database error. It means that the table you are attemping to read is not ready, because you attemp to acces to it before it is created:

class LatestBlogEntries(Feed):current_site = Site.objects.get_current()  <---- this line

You shoud load the static current_site variable in an independent function using post_migrate signal. There is an example in the docs

In case you find this overkill, there are workarrounds like:

  1. Catch the error. This will allow you to migrate, and in the next restart of the application it will read the object flawlessly.
    from django.db import ProgrammingErrorclass LatestBlogEntries(Feed):try:current_site = Site.objects.get_current()except ProgrammingError:pass
  1. Loading the variable in _init_ method if not defined.

This usually happens when this operation is modeled with the tables already created, and then the database is cleared to start from scratch.

https://en.xdnf.cn/q/119360.html

Related Q&A

list intersection algorithm implementation only using python lists (not sets)

Ive been trying to write down a list intersection algorithm in python that takes care of repetitions. Im a newbie to python and programming so forgive me if this sounds inefficient, but I couldnt come …

In keras\tensorflow, How adding CNN layers to last layer of ResNet50V2 that pre-train on imagenet

I am trying to drop the last layer and add a simple CNN instead like the following, model = Sequential() base_model = ResNet50V2(include_top=False, weights="imagenet", input_shape=input_shape…

How to get missing date in columns using python pandas [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 3 years ago.Improve…

vigenere cipher - not adding correct values

I want to get specific values from a for loop to add to another string to create a vigenere cipher.heres the code.userinput = input(enter message) keyword = input(enter keyword) new = for a in keyword…

Why isnt my output returning as expected?

So I wrote this code def diagsDownRight(M):n = len(M)m = [[] * (n - i - 1) + row + [] * i for i, row in enumerate(M)]return ([.join(col) for col in zip(*m)]), [.join(col[::-1]) for col in zip(*m)] def …

Django Stripe payment does not respond after clicking the Submit Payment button

I have an e-commerce application that Im working on. The app is currently hosted on Heroku free account. At the moment I can select a product, add it on the cart and can get up to the stripe form and t…

get file path using backslash (\) in windows in python [duplicate]

This question already has answers here:How can I put an actual backslash in a string literal (not use it for an escape sequence)?(4 answers)Closed 2 years ago.How to get result exactly the same format…

Printing progress bar on a console without the use of for -loop

I have a script written in python, where I have a statement:Process.open() //some parametersWhich executes a command and puts the output on the console ,where I do not know the time taken to execute t…

ModuleNotFoundError: No module named verovio

Hi there I would like to run my flask app in a container but I got stucked caused of a third party module. (I am using PyCharm)This is my docker file:FROM python:3-alpineMAINTAINER fooCOPY app /appWORK…

Python: TypeError: list object is not callable on global variable

I am currently in the process of programming a text-based adventure in Python as a learning exercise. I want "help" to be a global command, stored as values in a list, that can be called at (…