django removing hardcoded URLs in template --- 使用变量,把url放在变量中 {% url 'namespace:name' %}

1 urlpatterns = [
2     url(r'^admin/', admin.site.urls),
3     url(r'^votes/', include("polls.urls", namespace="polls")),
4 ]
/myproject/urls.py
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 '''
 5 @version:
 6 @author: leo Yang
 7 @license: none
 8 @contact: yangliw3@foxmail.com
 9 @site:
10 @software:PyCharm
11 @file:urls.py
12 @time(UTC+8):16/7/29-12:28
13 '''
14 
15 from django.conf.urls import url
16 from django.contrib import admin
17 from . import views
18 
19 urlpatterns = [
20     url(r'^admin/', admin.site.urls),
21     url(r'^index/', views.index, name="index"),
22     url(r'^detail/', views.detail, name="detail"),
23     url(r'^choice/', views.choice, name="choice"),
24     url(r'^result/', views.result, name="result"),
25 ]
/projectname/polls/urls.pyy
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>this is index page</title>
 6 </head>
 7 <body>
 8     <li><a href="{% url 'polls:index' %}">{% url 'polls:index' %}</a> </li>
 9     <li><a href="{% url 'polls:detail' %}">{% url 'polls:detail' %}</a> </li>
10     <li><a href="{% url 'polls:choice' %}">{% url 'polls:detail' %}</a> </li>
11     <li><a href="{% url 'polls:result' %}">{% url 'polls:result' %}</a> </li>
12     <li><a href="http://www.baidu.com">url:www.baidu.com</a></li>
13 
14 </body>
15 </html>
/projectname/polls/templates/index.html
 1 from django.shortcuts import render
 2 from django.http import HttpResponse
 3 from django.shortcuts import render,get_object_or_404,get_list_or_404
 4 
 5 # Create your views here.
 6 
 7 
 8 def index(request):
 9     ret_render = render(request, "polls/index.html")
10     return ret_render
11     return HttpResponse("this is index page")
12 
13 
14 def detail(request):
15     return HttpResponse("this is detail page")
16 
17 
18 def choice(request):
19     return HttpResponse("this is choice page")
20 
21 
22 def result(request):
23     return HttpResponse("this is result page")
/profectname/polls/views.py
原文地址:https://www.cnblogs.com/fepapa/p/5718828.html