Django根项目URL名称空间不起作用 [英] Django root project url namespace not working

查看:96
本文介绍了Django根项目URL名称空间不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定将首页(例如主要目标网页和关于我页面等)放在我项目的根目录,而不是其他应用程序。这意味着项目看起来像这样:

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

我的urls.py看起来像这样:

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>

我收到此错误:

NoReverseMatch at /
'Hello_World' is not a registered namespace

我在做什么错?预先感谢。

What am I doing wrong? Thanks in advance.

推荐答案

urls.py在您的settings.py
中设置为根URL。可能看起来像这样

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'.

您不能为根URL命名空间,因为只能有一个根URL。应用程序存在。

You cant namespace your root url because there can be only one root url.Namesapcing is done only when multiple app exists.

相反,您可以提及url的名称并使用它。

Instead you can mention the name of url and use it.

Ex: <a href="{% url 'index' %}">Home</a> 

以上内容适用于所有模板和所有没有命名空间的应用,因为href首先尝试在项目的urls.py文件中匹配名称索引

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'),.

django的原因django错误提示名称空间不匹配,因为它搜索其他应用程序的urls.py文件名称空间,因为它与app_name ='Hello_World'不匹配,否则显示错误。

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.

这篇关于Django根项目URL名称空间不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆