Django-用户认证组件

创建用户:

命令创建:

python manage.py createsuperuser    #超级用户
python manage.py createuser         #普通用户

视图创建

from django.contrib.auth.models import User

User.objects.create_user(username="bob",password=123)       #普通用户
User.objects.create_superuser(username="bob",password=123)  #超级用户

登录

from django.contrib import auth

去auth_user表中去验证用户名和密码,如果成功返回用户的一个对象,失败则返回None

user = auth.authenticate(username=用户名, password=用户密码)

将用户信息(session之类的东东)和request做绑定,并设置为全局变量

auth.login(request, user)

之后可以通过request.user.username或者request.user.last_login等进行取值之类的操作

request.user.is_authenticated

查看用户是否登录成功

注销

auth.logout(request)

案例:

from django.contrib import auth
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User

def login(request):
    if request.method == "POST":
        username = request.POST.get("user")
        password = request.POST.get("pwd")
        user = auth.authenticate(username=username, password=password)
        print("login=======================", user)
        if user:  # 验证成功后
            auth.login(request, user)
            return redirect("/book/")
    else:
        return redirect("/login/")

def book(request):
    book = Book.objects.all()
    print(request.user, '我是user对象')
    if request.user.is_authenticated:
        return render(request, "book.html", {"book": book})
    else:
        return redirect('/login/')

def logout(request):
    auth.logout(request)
    return redirect("/login/")

def adduser(request):
    User.objects.create_user(username="bob",password=123)
    return redirect("/login/")

 

发表评论