8👍
This error turns out (usually) to be caused, ultimately, by failing to create the initial migration for a new app. the error was resolved by running $ ./manage.py makemigrations <my new app module name> && migrate
NOTE: makemigrations
DOES NOT AUTOMATICALLY CREATE THE INITIAL MIGRATION FOR NEW APPS
1👍
This error happened to me because I was trying to run a piece of code that accessed the database when Django starts.
# file name: blog/apps.py
from django.apps import AppConfig
class BlogConfig(AppConfig):
name = 'blog'
def ready(self):
from .business import markdown_to_html
markdown_to_html.refresh_posts() # This method access the database.
Then, when I executed the tests: python manage.py test
, this code fragment was executed and I got the error you mentioned.
Why? It is explained here: https://docs.djangoproject.com/en/3.0/ref/applications/#django.apps.AppConfig.ready
As I needed to execute this method only once, I decided to create a management command.
Here is the code:
# file name: md_to_html.py
from django.core.management.base import BaseCommand
from blog.business import markdown_to_html
class Command(BaseCommand):
help = 'Convert posts written in markdown to html'
def handle(self, *args, **options):
markdown_to_html.refresh_posts()
self.stdout.write(self.style.SUCCESS('HTML files created'))
Before starting the Django project, I executed the command using the following line: python manage.py md_to_html
. In this way I ensured this code is executed only once in a safely.
Now when I run the tests I don’t get the error anymore.
Here you can find more information about how to create a custom management command in Django: https://docs.djangoproject.com/en/3.0/howto/custom-management-commands/
This link describes how to test a custom management command: https://docs.djangoproject.com/en/3.0/topics/testing/tools/#topics-testing-management-commands
- Unexpected error: replace() takes 2 positional arguments but 3 were given
- Do I need to close connection in mongodb?
0👍
In case you faced this issue while using pytest-django package, check that your haven’t created new migrations with --reuse-db
option in your pytest.ini
- Is it possible, in a django template, to check if an object is contained in a list
- How to add namespace url to a django-rest-framework router viewset
- Autocommit Migration from Django 1.7 to 1.8
- Buildout vs virtualenv + pip for django?