用户登录:
def logon(request): errors_list = [] if request.method == ‘POST‘: u = request.POST[‘uname‘] p = request.POST[‘upass‘] #验证用户 user = authenticate(username=u, password=p) if user is not None: auth_login(request, user) #登录成功后重定向到主页 return HttpResponseRedirect("/sinfors/") else: try: #检查用户密码是否正确 if not auth_User.objects.get(username = u).check_password(p): errors_list.append(u + ‘ password is not correct‘) #检查用户是否存在(auth_User.objects.get(username = u)) except auth_User.DoesNotExist: errors_list.append(u + ‘ does not exist‘) return render(request, ‘sinfors/login.html‘, {‘errors_list‘:errors_list})
页面添加认证:
#对页面增加验证 @login_required(login_url="/sinfors/logon/") def index(request): servers = infor.objects.all() #验证如果用户登录成功,则取相应的用户名显示在主页 if not request.user.is_anonymous(): user_loggedin = request.user else: user_loggedin = ‘Guest‘ context = {‘servers‘:servers,‘user_loggedin‘:user_loggedin} return render(request,‘sinfors/index.html‘,context)
新增用户,修改/验证密码:
#新建用户 user = User.objects.create_userusername=‘‘,password=‘‘,email=‘‘) user.save #不使用user.save() #重置密码 user.set_password(passeord=‘‘) user.save #检查用户输入的密码是否正确 user.check_password(‘password‘)
时间: 2024-10-13 11:28:37