views.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. from django.shortcuts import render, redirect
  2. from django.contrib.auth import authenticate, login, logout
  3. from django.http import HttpResponse, JsonResponse
  4. from django.views.decorators.csrf import ensure_csrf_cookie
  5. from .forms import UserLoginForm, UserRegisterForm
  6. # Create your views here.
  7. def user_login(request):
  8. ret = {}
  9. if request.method == 'POST':
  10. user_login_form = UserLoginForm(data=request.POST)
  11. print(request.POST)
  12. if user_login_form.is_valid():
  13. # .cleaned_data 清洗出合法数据
  14. data = user_login_form.cleaned_data
  15. # 检验账号、密码是否正确匹配数据库中的某个用户
  16. # 如果均匹配则返回这个 user 对象
  17. user = authenticate(username=data['username'], password=data['password'])
  18. if user:
  19. # 将用户数据保存在 session 中,即实现了登录动作
  20. login(request, user)
  21. ret['code'] = 1001
  22. ret['message'] = '登陆成功'
  23. return JsonResponse(ret)
  24. else:
  25. ret['code'] = 1002
  26. ret['message'] = '账号或密码输入有误。请重新输入'
  27. return JsonResponse(ret)
  28. else:
  29. ret['code'] = 1003
  30. ret['message'] = '账号或密码输入不合法'
  31. return JsonResponse(ret)
  32. elif request.method == 'GET':
  33. user_login_form = UserLoginForm()
  34. context = {'form': user_login_form}
  35. return render(request, 'Profile/login.html', context)
  36. else:
  37. ret['code'] = 1004
  38. ret['message'] = '请使用GET或POST请求数据'
  39. return JsonResponse(ret)
  40. def user_logout(request):
  41. logout(request)
  42. ret = {'code': 1001, 'message': '登出成功'}
  43. return JsonResponse(ret)
  44. def user_is_logged(request):
  45. ret = {}
  46. if request.user.is_authenticated:
  47. ret['code'] = 1001
  48. ret['message'] = '已登陆'
  49. return JsonResponse(ret)
  50. else:
  51. ret['code'] = 1002
  52. ret['message'] = '未登陆'
  53. return JsonResponse(ret)
  54. # 用户注册
  55. def user_register(request):
  56. ret = {}
  57. if request.method == 'POST':
  58. user_register_form = UserRegisterForm(data=request.POST)
  59. print(request.POST)
  60. if user_register_form.is_valid():
  61. new_user = user_register_form.save(commit=False)
  62. # 设置密码
  63. new_user.set_password(user_register_form.cleaned_data['password'])
  64. new_user.save()
  65. # 保存好数据后立即登录并返回博客列表页面
  66. ret['code'] = 1001
  67. ret['message'] = '注册成功'
  68. return JsonResponse(ret)
  69. else:
  70. ret['code'] = 1002
  71. ret['message'] = '注册表单输入有误。请重新输入'
  72. return JsonResponse(ret)
  73. elif request.method == 'GET':
  74. user_register_form = UserRegisterForm()
  75. context = {'form': user_register_form}
  76. return render(request, 'Profile/register.html', context)
  77. else:
  78. ret['code'] = 1003
  79. ret['message'] = '请使用GET或POST请求数据'
  80. return JsonResponse(ret)