index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> <!--style中的兩行使得列表橫向顯示,並且去掉了前面的·標識--> .nav{overflow:hidden} .nav li{float:left;list-style:none;margin:0 20px; } </style> </head> <body> <ul class='nav'> <li><a href='/'>首頁</a> </li> <li><a href={% url 'book' %}>讀書</a></li> <li><a href={% url 'movie' %}>電影</a></li> <li><a href={% url 'city' %}>同城</a></li> <li><a href={% url 'detail' book_id=8 catagory='health' %}>最火的文章</a></li> <li><a href={% url 'login' %}?next=/>登錄</a></li><!--注意參數傳遞的?next與前面沒有空格--> </ul> </body> </html>
urls.py
注意在views.py中使用{% url 'xxx' %}標簽時時,xxx指的是url名稱,需要在urls.py中通過name指定url名稱。
from . import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name='index'), path('book',views.book,name='book'), path('movie',views.movie,name='movie'), path('city',views.city,name='city'), path('book/book_detail/<book_id>/<catagory>',views.book_detail,name='detail'), path('login/',views.login,name='login') ]
views.py
from django.shortcuts import render from django.http import HttpResponse def index(request): context={} return render(request,'index.html',context=context) def login(request): next=request.GET.get('next') text='登錄頁面,登錄完成后要跳轉的url是%s'%next return HttpResponse(text) def book(request): return HttpResponse('讀書頁面') def book_detail(request,book_id,catagory): text='您獲取的圖書id是%s,分類是%s'%(book_id,catagory) return HttpResponse(text) def movie(request): return HttpResponse('電影頁面') def city(request): return HttpResponse('同城頁面')
頁面效果
每一個列表同時又是鏈接,點擊可跳轉到對應的頁面。