django基础(七)之路由名称

首先看urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    #url(r'^login/', views.Home.as_view()), ###针对类的固定用法
    #url(r'^home',views.home)
    url(r'^home/',views.Home.as_view()),
    #url(r'^detail-(\d+)-(\d+).html',views.detail),
    url(r'^cccc/',views.detail,name='detail')        ###指定name
]

 

视图函数views.py

def detail(request,nid):
    # print (request.path_info)
    #
    # v = reverse('detail',args=(90,))
    # print (v)
    return render(request, 'detail.html')

 

detail.html

 

说明:
①、detail.html中画圈的部分(action),共有三种写法:
  A、如图上所示:<form action="{{ request.path_info }}" method="post">     ## request.path_info 为固定用法,意思为打印当前访问的url目录

  

#urls.py

urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^cccc/(\d+)',views.detail,name='detail') ###此处的链接目录为 /cccc/任意数字 ]

#views.py
def detail(request,nid):
  print (request.path_info)
  return render(request, 'detail.html')

此时,则需要给views里的detail函数传一个参数,来代表 /cccc/任意数字 这个url的任意数字,如图:

 

访问的url: http://127.0.0.1:8000/cccc/14(13)/   

 

 

②、其他都不变,只有 html里的action 这里做了改变<form action="{% url 'detail' 3 %}" method="post">

{% url 'detail' 3 %} 为固定写法,表示从 urls.py 里获取name为detail的 链接进行访问,无论下图中红色框内
的值怎么变,这里访问的仍旧是name为detail的这个url,这里同样需要为视图函数里的detail函数传入一个参数(根据r'^cccc/(\d+)' 而来)

 


但是,此时访问http://127.0.0.1:8000/cccc/14/,提交后,所有的页面都会被重定向到http://127.0.0.1:8000/cccc/3/

因为 html中将此页面的post请求重定向到了http://127.0.0.1:8000/cccc/3/(由{% url 'detail' 3 %}得出)

 

 

重定向到指定页面

结果为

 

依次类推,如果访问url: http://127.0.0.1:8000/cccc/14/9 

urls.py

 

视图函数views.py需要传两个参数

detail.html (红色圆圈中同样需要传两个参数,但是<form action="{{ request.path_info }}" method="post">则不变)

换成{% url 'detail' 3 3 %} 方式则需要传两个参数

结果:

 

 同样:视图函数views.py也可以这样写

html

 

总结

 

posted @ 2018-04-28 11:08  FRESHMANS  阅读(181)  评论(0)    收藏  举报