目的: 打开http://127.0.0.1:8000/home 点击查看详情转到 http://127.0.0.1:8000/detail-1-1.html实现查看具体信息
一,利用url路由系统的正则表达式传参数
url(r'^detail-(?P<uid>d+)-(?P<nid>d+).html',views.detail),
def detail(request,uid,nid):
return
urls:
from django.contrib import admin from django.urls import path from cmbd import views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), path('home/', views.home), path('home', views.home), url(r'^detail-(?P<uid>d+)-(?P<nid>d+).html',views.detail), ]
views:
from django.shortcuts import render,redirect user_dict = { '1':{'name':'hrg','email':'hrg@163.com','pwd':'123'}, '2':{'name':'eric','email':'hrg@163.com','pwd':'111'}, '3':{'name':'hhh','email':'hrg@163.com','pwd':'222'}, '4':{'name':'kkk','email':'hrg@163.com','pwd':'123'}, } def home(request): return render(request,'home.html',{'user_dict':user_dict,}) def detail(request,uid,nid): detail_dict = user_dict[uid] print(detail_dict) return render(request,'detail.html',{'detail_dict':detail_dict,})
templates:
home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> {% for k,v in user_dict.items %} <li> <span>id:{{ k }}姓名:{{ v.name }}</span> <a href="/detail-{{ k }}-1.html">查看详情</a> </li> {% endfor %} </ul> </body> </html> detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用户详情:</h1> <ul> {% for k,v in detail_dict.items %} <li>{{ k }}:{{ v }}</li> {% endfor %} </ul> </body> </html>
二,利用URL地址栏?功能传参数
/detail?uid=1&pid=2
urls:
from django.contrib import admin from django.urls import path from cmbd import views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), path('home/', views.home), path('home', views.home), path('detail',views.detail), ]
views:
from django.shortcuts import render,redirect user_dict = { '1':{'name':'hrg','email':'hrg@163.com','pwd':'123'}, '2':{'name':'eric','email':'hrg@163.com','pwd':'111'}, '3':{'name':'hhh','email':'hrg@163.com','pwd':'222'}, '4':{'name':'kkk','email':'hrg@163.com','pwd':'123'}, } def home(request): return render(request,'home.html',{'user_dict':user_dict,}) def detail(request): uid = request.GET.get('uid') #获取home.html中/detail?uid={{ k }}传来的值 detail_dict = user_dict[uid] print(detail_dict) return render(request,'detail.html',{'detail_dict':detail_dict,})
templates:
home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> {% for k,v in user_dict.items %} <li> <span>id:{{ k }}姓名:{{ v.name }}</span> <a href="/detail?uid={{ k }}">查看详情</a> </li> {% endfor %} </ul> </body> </html> detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用户详情:</h1> <ul> {% for k,v in detail_dict.items %} <li>{{ k }}:{{ v }}</li> {% endfor %} </ul> </body> </html>