auth模块基础方法

2019-07-30  本文已影响0人  warmsirius

写在前面

这几天的项目用到了挺多auth模块的内容,今天来总结一下django中auth模块的一些基础的用法。

参考博客

auth模块的基础方法

from django.contrib import auth
python manage.py createsuperuser
python manage.py createuser
# 让authenticate不关联is_active
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend']
user = auth.authenticate(username=username, password=pwd)

from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        login(request, user)
        # Redirect to a success page.
        ...
    else:
    # Return an 'invalid login' error message.
        ...
from django.contrib.auth import logout

def logout_view(request):
    logout(request)
    # Redirect to a success page.

  def my_view(request):
    if not request.user.is_authenticated():
    return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

class Home(views.View):

    @method_decorator(login_required)
    def get(self, request):
        return render(request, 'home.html')
from django.contrib.auth.models import User

user = User.objects.create_user(username = '用户名', password = '密码', email = '邮箱', ...)
# create_superuser() # 创建超级用户

from django.contrib.auth.hashers import check_password
user = User.objects.get(username=username)
pwd = user.password

print(user)

# 第一个参数为明文密码,第二个参数为加密后的密
if check_password(password, pwd):
    # 用户名密码正确
    pass
user.set_password(password='')  
user.save()
上一篇下一篇

猜你喜欢

热点阅读