from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import ensure_csrf_cookie from .forms import UserLoginForm, UserRegisterForm # Create your views here. def user_login(request): ret = {} if request.method == 'POST': user_login_form = UserLoginForm(data=request.POST) print(request.POST) if user_login_form.is_valid(): # .cleaned_data 清洗出合法数据 data = user_login_form.cleaned_data # 检验账号、密码是否正确匹配数据库中的某个用户 # 如果均匹配则返回这个 user 对象 user = authenticate(username=data['username'], password=data['password']) if user: # 将用户数据保存在 session 中,即实现了登录动作 login(request, user) ret['code'] = 1001 ret['message'] = '登陆成功' return JsonResponse(ret) else: ret['code'] = 1002 ret['message'] = '账号或密码输入有误。请重新输入' return JsonResponse(ret) else: ret['code'] = 1003 ret['message'] = '账号或密码输入不合法' return JsonResponse(ret) elif request.method == 'GET': user_login_form = UserLoginForm() context = {'form': user_login_form} return render(request, 'Profile/login.html', context) else: ret['code'] = 1004 ret['message'] = '请使用GET或POST请求数据' return JsonResponse(ret) def user_logout(request): logout(request) ret = {'code': 1001, 'message': '登出成功'} return JsonResponse(ret) def user_is_logged(request): ret = {} if request.user.is_authenticated: ret['code'] = 1001 ret['message'] = '已登陆' return JsonResponse(ret) else: ret['code'] = 1002 ret['message'] = '未登陆' return JsonResponse(ret) # 用户注册 def user_register(request): ret = {} if request.method == 'POST': user_register_form = UserRegisterForm(data=request.POST) print(request.POST) if user_register_form.is_valid(): new_user = user_register_form.save(commit=False) # 设置密码 new_user.set_password(user_register_form.cleaned_data['password']) new_user.save() # 保存好数据后立即登录并返回博客列表页面 ret['code'] = 1001 ret['message'] = '注册成功' return JsonResponse(ret) else: ret['code'] = 1002 ret['message'] = '注册表单输入有误。请重新输入' return JsonResponse(ret) elif request.method == 'GET': user_register_form = UserRegisterForm() context = {'form': user_register_form} return render(request, 'Profile/register.html', context) else: ret['code'] = 1003 ret['message'] = '请使用GET或POST请求数据' return JsonResponse(ret)