1 from django.shortcuts import render, redirect
2 from django.http import HttpResponseRedirect
3 from django.contrib.auth.models import User
4 from django.contrib.auth import authenticate,login,logout
5 from django.contrib.auth.models import AnonymousUser
6
7 # Create your views here.
8 # 主页
9 def index(request,):
10 username = request.user
11 return render(request,'Myapp/index.html',locals())
12
13 # 登录
14 def tologin(request):
15 if request.method == 'POST' and request.POST:
16 data = request.POST
17 username = data.get('username')
18 password = data.get('password')
19 n = authenticate(username=username,password=password)
20 if n:
21 # 登陆成功即可获取当前登录用户,返回主页
22 login(request,user=n)
23 return redirect('/')
24 # 失败重定向到登录页
25 return render(request, 'myApp/login.html')
26
27 # 注册
28 def register(request):
29 if request.method == 'POST' and request.POST:
30 data = request.POST
31 username = data.get("username")
32 password = data.get("password")
33 # 校验注册,名字不可重复
34 u = User.objects.filter(username=username).first()
35 if u:
36 info = '该用户名已被注册'
37 return render(request,'Myapp/ERROR.html',{'info':info})
38 else:
39 # 注册成功,创建用户
40 User.objects.create_user(
41 username=username,
42 password=password
43 )
44 # 重定向到登录页面
45 return HttpResponseRedirect('/tologin/')
46 # 注册失败,重新注册
47 return render(request,'Myapp/register.html')
48
49 def lagout(request):
50 logout(request)
51 return redirect('/')