定义视图
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.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect # 以类方式定义 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")
响应
返回字符串
return HttpResponse("字符串")
返回html
return render(request, "html模板路径", {data: data})
重定向
return redirect("/url路径")
取值
获取单一值
# get方式 user = request.GET.get("user") # post方式 user = request.POST.get("user")
获取多个值
v2 = request.POST.getlist("favor")
时间: 2024-10-11 10:32:30