Python之路60-Django 視圖
阿新 • • 發佈:2017-05-19
python
目錄
一、定義視圖
二、響應
一、定義視圖
views.py
from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect # 以函數方式定義 def login(request): if request.method == "GET": return render(request, "login.html") elif request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") if user == "admin" and pwd == "123": return redirect("/index/") else: return render(request, "login.html") else: # PUT,DELETE,HEAD... return redirect("/index/") # 以類方式定義 from django.views import View class Home(View): # 父類會通過dispatch去獲取request信息並判斷,然後執行相關方法,返回數據也要通過dispatch方法,before、after可以再執行方法前做一些自定義操作 def dispatch(self, request, *args, **kwargs): # 調用父類中的dispatch print("before") result = super(Home, self).dispatch(request, *args, **kwargs) print("after") return result def get(self, request): print(request.method) return render(request, "home.html") def post(self, request): print(request.method) return render(request, "home.html")
二、響應
1.返回字符串
return HttpResponse("字符串")
2.返回html
return render(request, "html模板路徑", {data: data})
3.重定向
return redirect("/url路徑")
本文出自 “八英裏” 博客,請務必保留此出處http://5921271.blog.51cto.com/5911271/1927645
Python之路60-Django 視圖