内置auth 的使用,用超级用户创建
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="post"> {% csrf_token %} <p> <label for="">用户名</label> <input type="text" name="username"> </p> <p> <label for="">密码</label> <input type="password" name="password"> </p> <p> <input type="submit" value="提交"> </p> </form> </body> </html>
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>这是{{ user.username }}index</h1> <h3><a href="/logout/">注销</a></h3> </body> </html>
views.py
from django.shortcuts import render,redirect,HttpResponse from django.contrib import auth from django.contrib.auth.decorators import login_required # Create your views here. def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') # 判断用户名和密码是否正确 user = auth.authenticate(request,username=username,password=password) if user: # 将登陆的用户封装到request auth.login(request, user) return redirect('/index/') return render(request, 'login.html') @login_required def index(request): print(request.user.username) ret = request.user.is_authenticated() print(ret) return render(request,'index.html') def logout(request): auth.logout(request) return redirect('/login/') def register(request): #导入auth_user表 from django.contrib.auth.models import User #创建一个用户 # User.objects.create(username='xiaoming',password='123456')#不用这个 user_obj = User.objects.create_user(username='xiaoli',password='123456') #检查当前密码,打印True Flase ret = user_obj.check_password('123123') print(ret) #修改密码 user_obj.set_password('111111') user_obj.save() return HttpResponse('注册成功')
url
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login',views.login), url(r'^index',views.index), url(r'^logout',views.logout), url(r'^register',views.register), ]
使用默认的超级用户表
models中不用创建表
生成迁移并执行迁移
python mange.py makemigrations python manage.py migrate
创建超级用户 python manage.py createsuperuser
然后运行 python manage.py runserver