Python 如何在 Django 模板中使用 href 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17200389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use the href attribute in django templates
提问by avorum
When I try to use a link in my Django template from /appname/index/to get to /appname/detail/###I am instead getting to /appname/index/detail/###which is not what I'm trying to get so my app can't find it in the urlconf of course.
当我尝试在我的 Django 模板中使用一个链接/appname/index/来到达时,/appname/detail/###我得到的/appname/index/detail/###不是我想要得到的,所以我的应用程序当然无法在 urlconf 中找到它。
First the urls.py line for the detail page
首先是详细信息页面的 urls.py 行
url(r'detail/(?P<jobID>\d+)/$', 'appname.views.detail')
Additionally, the root urlconf
此外,根 urlconf
urlpatterns = patterns('',
url(r'^appname/', include('appname.urls')),
url(r'^admin/', include(admin.site.urls)),
)
Next the template code trying to get there
接下来是试图到达那里的模板代码
{% for job in jobList %}
<a href="detail/{{ job.id }}/">{{ job.name }}</a>
I'm not sure what else might be applicable information, just ask if you would like to see something else. I also tried :
我不确定还有什么可能是适用的信息,请问您是否想查看其他信息。我也试过:
<a href="{% url 'appname.views.detail' %}/{{ job.id }}">{{ job.name }}</a>
But that didn't work either. Thank you in advance for any help.
但这也不起作用。预先感谢您的任何帮助。
采纳答案by Aamir Adnan
Add /at start in href:
/在开始时添加href:
<a href="/appname/detail/{{ job.id }}/">{{ job.name }}</a>
And for the urltag to work you need to do it like this:
为了使url标签起作用,您需要这样做:
<a href="{% url 'appname.views.detail' jobID=job.id %}">{{ job.name }}</a>
回答by Patrick Mutuku
From my experience, as long as you have defined the url of the page the hreftag should lead to in urls.py, include the absolute path in the format below.
根据我的经验,只要您定义了href标签应该指向的页面的 url in urls.py,请按以下格式包含绝对路径。
Site name: yyyy.com
Url of page to redirect to in urls.py: yyyy.com/signup/
Sample link: <a href="/signup/">Signup</a>
You will notice that what goes inside the href tag is sort of appended to the current url. For more dynamic links, you can use some python as of DTL guidelines.
您会注意到 href 标签内的内容有点附加到当前网址。对于更多动态链接,您可以使用一些 Python 作为 DTL 指南。
回答by Arunkumar Arjunan
Nice this works perfectly, I added <h2><a href="/index.html">Click here to go to Index page</a></h2>instead of <h2><a href="index.html">Click here to go to Index page</a></h2>
很好,这很完美,我添加了<h2><a href="/index.html">Click here to go to Index page</a></h2>而不是<h2><a href="index.html">Click here to go to Index page</a></h2>

