开发者

What happen when I add a Django app to INSTALLED_APPS?

开发者 https://www.devze.com 2022-12-16 10:38 出处:网络
Here is the situation.I have a django project with two installed apps.Both apps appear to function properly if they are installed independently of each other.

Here is the situation. I have a django project with two installed apps. Both apps appear to function properly if they are installed independently of each other.

However if I list both apps in the settings.INSTALLED_APPS the reverse() function seems to break for urls i开发者_StackOverflow社区n the first app. So this leads me to believe that a bug in the second app is causing the problem.

If I simply remove app_2 from the settings.INSTALLED_APPS, app_1's url reverse() begins working again. So the question becomes what "Magic" is happening when I add app_2 to the settings.INSTALLED_APPS? Where should I be looking in app_2 for code causing this problem?

UPDATE:

I have narrowed down the problem a little, but it just gets stranger. app_2 has an admin.py file that defines a few custom admin views. In that file is a line that calls reverse:

reverse('init_script_view', args=['id_content'])

As long as that line is in the admin.py file all calls to reverse() fail with a NoReverseMatch exception. If I remove that line, everything seems to work fine.


Nothing particular happens when you add an app to INSTALLED_APPS, but the main thing that affects you is that its views are checked when you call reverse().

The way reverse works is to import all the views in the project, and see which ones match the URL name you have given. However, it is quite fragile, and if any of the views cause an error for some reason, or can't be imported, the reverse call will fail.

The fact that it is only failing once you include app2 indicates that there is an issue with the views in app2 somewhere. Try importing them individually from the shell and see what errors you get.

Edited after update Thanks for the extra detail. I have seen this before in my own code. It is probably because the admin files are being imported before the urlconf is processed, so this reverse gives an error. Try moving the admin.autodiscover() line down to the very bottom of urls.py, so that it is the last line in that file.


Without seeing the code, it's hard to say for sure, but I would guess that the urls.py of app_1 and app_2 contain the same name for different urls, e.g.:

app_1/urls.py:
  ...
  url(r'^app_1/foo/$', 'app_1.views.foo', name='foo')
  ...

app_2/urls.py:
  ...
  url(r'^app_2/foo/$', 'app_2.views.foo', name='foo')
  ...

If you clean up those names (the most common convention I've seen is appname_viewname) it should start working.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号