Django-views,用户认证,login_requierd()
分别是认证,登入,注销的功能
authenticated():验证是否登录
user = authenticate(username='someone',password='somepassword')
login():登入,并且创建cookie,session
login(request, user)
logout():注销,清除session
logout(request,)
user对象方法
user对象的is_authenticated()方法
def my_view(request): if not request.user.is_authenticated(): return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
创建用户方法
from django.contrib.auth.models import User user = User.objects.create_user(username='',password='',email='')
修改密码
user = User.objects.get(username='') user.set_password(password='') user.save
示例一:修改密码
@login_required def set_password(request): user = request.user state = None if request.method == 'POST': old_password = request.POST.get('old_password', '') new_password = request.POST.get('new_password', '') repeat_password = request.POST.get('repeat_password', '') if user.check_password(old_password): if not new_password: state = 'empty' elif new_password != repeat_password: state = 'repeat_error' else: user.set_password(new_password) user.save() return redirect("/log_in/") else: state = 'password_error' content = { 'user': user, 'state': state, } return render(request, 'book/set_password.html', content)
示例二:ajax提交登录并验证
def log_in(request): if request.is_ajax(): username=request.POST.get("username") password=request.POST.get("password") valid_code=request.POST.get("valid_code") ajax_response={"user":None,"errors":""} if valid_code.upper()==request.session.get("valid_code").upper(): user=authenticate(username=username,password=password) # 用户验证 if user: login(request,user) # 执行后,相当于设定了cookie和session ajax_response["user"]=user.username else: ajax_response["errors"]="用户名或者密码错误" else: ajax_response["errors"]="验证码错误" return HttpResponse(json.dumps(ajax_response)) return render(request,"login.html")
django也为我们设计好了一个用于此种情况的装饰器:login_requierd(),实现跟is_authenticated()同样功能
from django.contrib.auth.decorators import login_required @login_required def my_view(request): ...
若用户没有登录,则会跳转到django默认的 登录URL '/accounts/login/ ' (这个值可以在settings文件中通过LOGIN_URL进行修改)。并传递 当前访问url的绝对路径 (登陆成功后,会重定向到该路径)。