问题
I decided to have the front pages such as the main landing page and the 'about me' page etc. at the root of my project instead as a different app. This means the project looks like this:
/django-helloworld
/Hello_World
__init__.py
url.py
views.py
wsgi.py
/static
style.css
/templates
index.html
My urls.py looks like this:
from django.conf.urls import url, include
from django.contrib import admin
from . import views
app_name = 'Hello_World'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^admin/', admin.site.urls),
The problem is, when I try to point to a url in my template, it works by doing:
<a href="{% url 'index' %}">Home</a>
But if I try referencing the namespace like so:
<a href="{% url 'Hello_World:index' %}">Home</a>
I get this error:
NoReverseMatch at /
'Hello_World' is not a registered namespace
What am I doing wrong? Thanks in advance.
回答1:
urls.py you are refering to is set as root url in your settings.py It probably looks like this
ROOT_URLCONF = 'Hello_World.urls'.
You cant namespace your root url because there can be only one root url.Namesapcing is done only when multiple app exists.
Instead you can mention the name of url and use it.
Ex: <a href="{% url 'index' %}">Home</a>
The above will work in all of your templates and in all the apps WITHOUT namespacing because the href will first try for the urls.py file of your project where it will match the name index
url(r'^$', views.IndexView.as_view(), name='index'),.
The Reason django for django error saying namespace not matched beacuse it searches for other apps urls.py file for namespace and because it doesnt match app_name= 'Hello_World' else where the error is displayed.
来源:https://stackoverflow.com/questions/39933269/django-root-project-url-namespace-not-working