重写 AppConfig.ready()

尝试了解 Django 的基本知识,即应用程序是如何工作的。 文档: < a href = “ https://docs.djangoproject.com/en/stat/ref/apps/# method”rel = “ norefrer”> https://docs.djangoproject.com/en/stable/ref/applications/#methods

在 AppConfig 类的代码中,我们可以看到:

def ready(self):
"""
Override this method in subclasses to run code when Django starts.
"""

这是我的例子:

My _ app/apps.py

class MyAppConfig(AppConfig):
name = 'my_app'


def ready(self):
print('My app')

我只是想让现成的方法起作用。也就是说,当 Django 找到 my _ app 时,让它运行 ready 方法。

该应用程序在 INSTALLED _ APPS 中注册。

我执行‘ python management. py runserver’,并且不打印任何内容。

如果我在 ready 方法中放置了一个断点,调试器不会在那里停止。

你能帮助我: 我在这里理解的错误是什么。提前谢谢你。

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'my_app',
]

我创造了一个视角

My _ app/views.py

def index(request):
print('Print index')

Urls.py

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', my_app_views.index, name='home')
]

好的,视图正在工作。这意味着应用程序已注册。

28240 次浏览

You need to do one of two things. Either explicitly say which AppConfig you want in INSTALLED_APPS:

INSTALLED_APPS = [
'my_app.apps.MyAppConfig'
]

Or, define a default_app_config in the __init__.py of your app:

# my_app/__init__.py
default_app_config = 'my_app.apps.MyAppConfig'

(and leave INSTALLED_APPS as-is).

As it is currently Django can't find any AppConfig for the app and just assumes there isn't one. So your views etc. will work, but the ready() method will never get called.

Here's the relevant section of the documentation.

Edit: as of Django 3.2, specifying a default_app_config is no longer necessary, and is in fact deprecated - so this answer is redundant for anyone using Django 3.2 or later.