环境:python 3.6.4 django 1.1.10
urlpatterns = [ url(r'^index.html$', views.index, name="ind"), url(r'^books.html$', views.books, name="books"), url(r'^book/(w+)$', views.openbook, name="openbook"), url(r'^books/(?P<booknumber>)', views.book, name="book"), url(r'^', views.index, name="default"),
这一部分展示了如何用传字典类型数据使用的占位符(?P<booknumber>),一定要有括号和?P
def index(request):
url=reverse('ind')
print(url)
return HttpResponse('<h1>图书馆欢迎你!</h1>')
def books(request):
return render(request,'lib_books.html')
views.books() 对于返回这个页面,
html对应代码
<h1 url="{% url 'ind' %}">这里有很多书</h1> <ul> <li><a href="/lib/book/123456">三体</a></li> <li><a href="/lib/book/000001">西游记</a></li>
对于再模板中接收别名,可以接收自己和所在urlpattern中所有别名
按照:url(r'^book/(w+)$', views.openbook, name="openbook"),进入openbook()
def openbook(request,booknumber):
print('booknumber is ;',booknumber)
url = reverse('book', kwargs={'booknumber': booknumber})
print(url)
return redirect(url)
这里利用reverse(),生成url()其中的第一个参数,可以是kwarg={,},也可以是arg=(,),前者对应的url中正则参数一定腰带(?P<>)分组,而arg则直接进入正则表达式()分组
def book(request,booknumber):
import re
booknumber=re.findall(r'd+$',request.path)
print(request.path,'bm is :',booknumber)
books={'123456':'santi','000001':'西游记'}
bookname=books.get(booknumber[0])
return render(request,'三体.html',{'bookname':bookname})