示例
from django.shortcuts import render from django.contrib.auth import authenticate,login,logout from django.http import HttpResponse,JsonResponse,HttpResponseRedirect from django.urls import reverse # Create your views here. def login_view(request): if request.method=="GET": return render(request,"public/login.html") else: username=request.POST.get("username","")#给一个空的默认值防止报错 userpass=request.POST.get("password","")# print(username,userpass) user = authenticate(username=username,password=userpass) ret = {"status":0,"errmsg":""} #定义一个输出,字典转成json格式传给前端,json格式对于前端js就是一个对象可以进行处理,定义status=0为正常 if user: login(request,user) # return HttpResponse("用户登录成功") ret['next_url'] = request.GET.get("next") if request.GET.get("next",None) else "/dashboard" else: ret['status'] = 1 ret['errmsg']="用户名或密码错误,请联系管理员" return JsonResponse(ret) def logout_view(request): #退出登录 logout(request) return HttpResponseRedirect(reverse("user_login")) #reverse 把url的名字转换成url
url配置
from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^login/$', views.login_view, name='user_login'), url(r'^logout/$', views.login_view, name='user_logout'), url(r'^user/list/$', views.login_view, name='user_list'), ]
dashboard的配置
from django.shortcuts import render # Create your views here. from django.http import HttpResponse,JsonResponse from django.template import Context,loader from django.contrib.auth.decorators import login_required @login_required #首页认证 def index(request): return render(request,"index.html")
1.函数视图
接收一个request参数(HttpRequest)
返回一个HttpResponse对象
2.QueryDict对象
GET/POST
get请求数据放在request.GET里面
post请求数据放在request.POST里面
例如 ?a=1&b=2&b=3
取值方法: request.GET.get("a") request.GET.get("b"),
request.POST.get("a") request.POST.get("b"),