本文介绍了重写AppConfig.ready()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 尝试了解Django的基础知识。即应用程序如何工作。 docs: https://docs.djangoproject.com/en / stable / ref / applications /#methods Trying to catch the basics of Django. Namely how Applications work.The docs: https://docs.djangoproject.com/en/stable/ref/applications/#methods在AppConfig类的代码中,我们可以读取:And in the code of the class AppConfig we can read: 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方法。 I just want to make the ready method work. That is, when Django finds my_app, let it run the ready method. 该应用已在INSTALLED_APPS中注册。 The app is registered in INSTALLED_APPS. 我执行 python manage.py runserver。不会打印任何内容。I execute 'python manage.py runserver'. And nothing is printed.如果我在ready方法中放置一个断点,调试器就不会停在那里。If I place a breakpoint inside the ready method, the debugger don't stop there.您能帮我吗:我在这里理解的错误是什么? Could you help me: what is my mistake in understanding here. Thank you in advance.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')]好,视图正在运行。 推荐答案您需要执行以下两项操作之一。在 INSTALLED_APPS 中明确声明要使用哪个 AppConfig :You need to do one of two things. Either explicitly say which AppConfig you want in INSTALLED_APPS:INSTALLED_APPS = [ 'my_app.apps.MyAppConfig']或者,在应用程序的 __ init __。py 中定义 default_app_config :Or, define a default_app_config in the __init__.py of your app:# my_app/__init__.pydefault_app_config = 'my_app.apps.MyAppConfig'(并保持 INSTALLED_APPS 不变)。由于目前Django无法为该应用程序找到任何 AppConfig ,因此仅假设没有。因此您的视图等将起作用,但是 ready()方法将永远不会被调用。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.这里是文档的相关部分。 这篇关于重写AppConfig.ready()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-30 15:10