http://www.baidu.cn/python/1/?i=1&p=new,只匹配「/python/1/」部分
url(r'^([0-9]+)/$', views.detail, name='detail'),
url(r'^(?P<id>[0-9]+)/$', views.detail, name='detail'),
from django.conf.urls import include, url urlpatterns = [ url(r'^', include('booktest.urls', namespace='booktest')), ]
請求http://www.baidu.cn/booktest/1/ 在sesstings.py中的配置: url(r'^booktest/', include('booktest.urls', namespace='booktest')), 在booktest應用urls.py中的配置 url(r'^([0-9]+)/$', views.detail, name='detail'), 匹配部分是:/booktest/1/ 匹配過程:在settings.py中與「booktest/」成功,再用「1/」與booktest應用的urls匹配
URL的反向解析
若是在視圖、模板中使用硬編碼的連接,在urlconf發生改變時,維護是一件很是麻煩的事情
解決:在作連接時,經過指向urlconf的名稱,動態生成連接地址
視圖:使用django.core.urlresolvers.reverse()函數
模板:使用url模板標籤
新建views1.py #coding:utf-8 from django.http import HttpResponse def index(request): return HttpResponse("你好") 在urls.py中修改配置 from . import views1 url(r'^$', views1.index, name='index'),
<!DOCTYPE html> <html> <head> <title></title> </head> <body> 找不到了 <hr/> {{request_path}} </body> </html>
DEBUG = False ALLOWED_HOSTS = ['*', ]
http://127.0.0.1:8000/test/
dict.get('鍵',default) 或簡寫爲 dict['鍵']
方法getlist():根據鍵獲取值html
dict.getlist('鍵',default)
def getTest1(request): return render(request,'booktest/getTest1.html') def getTest2(request): return render(request,'booktest/getTest2.html') def getTest3(request): return render(request,'booktest/getTest3.html')
url(r'^getTest1/$', views.getTest1), url(r'^getTest2/$', views.getTest2), url(r'^getTest3/$', views.getTest3),
<html> <head> <title>Title</title> </head> <body> 連接1:一個鍵傳遞一個值 <a href="/getTest2/?a=1&b=2">gettest2</a><br> 連接2:一個鍵傳遞多個值 <a href="/getTest3/?a=1&a=2&b=3">gettest3</a> </body> </html>
def getTest2(request): a=request.GET['a'] b=request.GET['b'] context={'a':a,'b':b} return render(request,'booktest/getTest2.html',context)
<html> <head> <title>Title</title> </head> <body> a:{{ a }}<br> b:{{ b }} </body> </html>
def getTest3(request): a=request.GET.getlist('a') b=request.GET['b'] context={'a':a,'b':b} return render(request,'booktest/getTest3.html',context)
<html> <head> <title>Title</title> </head> <body> a:{% for item in a %} {{ item }} {% endfor %} <br> b:{{ b }} </body> </html>
def postTest1(request): return render(request,'booktest/postTest1.html')
url(r'^postTest1$',views.postTest1)
<html> <head> <title>Title</title> </head> <body> <form method="post" action="/postTest2/"> 姓名:<input type="text" name="uname"/><br> 密碼:<input type="password" name="upwd"/><br> 性別:<input type="radio" name="ugender" value="1"/>男 <input type="radio" name="ugender" value="0"/>女<br> 愛好:<input type="checkbox" name="uhobby" value="胸口碎大石"/>胸口碎大石 <input type="checkbox" name="uhobby" value="跳樓"/>跳樓 <input type="checkbox" name="uhobby" value="喝酒"/>喝酒 <input type="checkbox" name="uhobby" value="登山"/>登山<br> <input type="submit" value="提交"/> </form> </body> </html>
def postTest2(request): uname=request.POST['uname'] upwd=request.POST['upwd'] ugender=request.POST['ugender'] uhobby=request.POST.getlist('uhobby') context={'uname':uname,'upwd':upwd,'ugender':ugender,'uhobby':uhobby} return render(request,'booktest/postTest2.html',context)
url(r'^postTest2$',views.postTest2)
<html> <head> <title>Title</title> </head> <body> {{ uname }}<br> {{ upwd }}<br> {{ ugender }}<br> {{ uhobby }} </body> </html>
#coding=utf-8 from django.http import HttpResponse def index(request): return HttpResponse('你好')
from django.http import HttpResponse from django.template import RequestContext, loader def index(request): t1 = loader.get_template('polls/index.html') context = RequestContext(request, {'h1': 'hello'}) return HttpResponse(t1.render(context))
from django.http import HttpResponse from datetime import * def index(request): response = HttpResponse() if request.COOKIES.has_key('h1'): response.write('<h1>' + request.COOKIES['h1'] + '</h1>') response.set_cookie('h1', '你好', 120) # response.set_cookie('h1', '你好', None, datetime(2016, 10, 31)) return response
在views1.py中 from django.http import HttpResponse,HttpResponseRedirect def index(request): return HttpResponseRedirect('js/') def index2(request,id): return HttpResponse(id) 在應用的urls.py中增長一個url對象 url(r'^([0-9]+)/$', views1.index2, name='index2'),
from django.core.urlresolvers import reverse def index(request): return HttpResponseRedirect(reverse('booktest:index2', args=(1,)))
from django.http import JsonResponse def index2(requeset): return JsonResponse({'list': 'abc'})
from django.shortcuts import render def index(request): return render(request, 'booktest/index.html', {'h1': 'hello'})
from django.shortcuts import redirect from django.core.urlresolvers import reverse def index(request): return redirect(reverse('booktest:index2'))
from django.shortcuts import * def detail(request, id): try: book = get_object_or_404(BookInfo, pk=id) except BookInfo.MultipleObjectsReturned: book = None return render(request, 'booktest/detail.html', {'book': book}) 將settings.py中的DEBUG改成False 將請求地址輸入2和100查看效果
from django.shortcuts import * def index(request): # list = get_list_or_404(BookInfo, pk__lt=1) list = get_list_or_404(BookInfo, pk__lt=6) return render(request, 'booktest/index.html', {'list': list}) 將settings.py中的DEBUG改成False
項INSTALLED_APPS列表中添加: 'django.contrib.sessions', 項MIDDLEWARE_CLASSES列表中添加: 'django.contrib.sessions.middleware.SessionMiddleware',
from django.shortcuts import render, redirect from django.core.urlresolvers import reverse def index(request): uname = request.session.get('uname') return render(request, 'booktest/index.html', {'uname': uname}) def login(request): return render(request, 'booktest/login.html') def login_handle(request): request.session['uname'] = request.POST['uname'] return redirect(reverse('main:index')) def logout(request): # request.session['uname'] = None # del request.session['uname'] # request.session.clear() request.session.flush() return redirect(reverse('main:index'))
主url: from django.conf.urls import include, url urlpatterns = [ url(r'^', include('booktest.urls', namespace='main')) ] 應用url: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'login/$', views.login, name='login'), url(r'login_handle/$', views.login_handle, name='login_handle'), url(r'logout/$', views.logout, name='logout') ]
<!DOCTYPE html> <html> <head> <title>首頁</title> </head> <body> 你好:{{uname}} <hr/> <a href="{%url 'main:login'%}">登陸</a> <hr/> <a href="{%url 'main:logout'%}">退出</a> </body> </html>
<!DOCTYPE html> <html> <head> <title>登陸</title> </head> <body> <form method="post" action="/login_handle/"> <input type="text" name="uname"/> <input type="submit" value="登陸"/> </form> </body> </html>
def login_handle(request): request.session['uname'] = request.POST['uname'] # request.session.set_expiry(10) # request.session.set_expiry(timedelta(days=5)) # request.session.set_expiry(0) # request.session.set_expiry(None) return redirect(reverse('main:index'))
SESSION_ENGINE='django.contrib.sessions.backends.db'
SESSION_ENGINE='django.contrib.sessions.backends.cache'
SESSION_ENGINE='django.contrib.sessions.backends.cached_db'
pip install django-redis-sessions
SESSION_ENGINE = 'redis_sessions.session' SESSION_REDIS_HOST = 'localhost' SESSION_REDIS_PORT = 6379 SESSION_REDIS_DB = 0 SESSION_REDIS_PASSWORD = '' SESSION_REDIS_PREFIX = 'session'
啓動:sudo redis-server /etc/redis/redis.conf 中止:sudo redis-server stop 重啓:sudo redis-server restart redis-cli:使用客戶端鏈接服務器 keys *:查看全部的鍵 get name:獲取指定鍵的值 del name:刪除指定名稱的鍵