您的位置:首页技术文章
文章详情页

python - 关于django的登陆成功后的view,使用login_required装饰后无法正常显示?

【字号: 日期:2022-08-08 14:17:45浏览:62作者:猪猪

问题描述

最近在学django,不过遇到一个奇怪的问题:登陆成功后,无法正确显示登陆后的view

这个是我的login view:

def login(request): ''' View of for users’ logging ''' if request.method == ’POST’:userform = UserForm(request.POST)if userform.is_valid(): username = userform.cleaned_data[’username’] password = userform.cleaned_data[’password’] confirm = UserProfile.objects.filter(username__exact=username, password__exact=password) positive = HttpResponseRedirect(reverse(’accounts:index’)) negative = HttpResponseRedirect(reverse(’accounts’)) return positive if confirm else negative else:userform = UserForm() dict_pass = {’userform’: userform} return render(request, ’accounts/login.html’, dict_pass)

认证通过后应该登陆的view:

@login_requireddef index(request): dict_pass = {} return render(request, ’accounts/index.html’, dict_pass)

如果不用装饰,那么是可以正常跳转的,但是用了装饰器就无法正常跳转到index页面了,用户名密码也没有输错,包导入也没有问题。

问之前我查了下相关的话题,没有人遇到过这种问题啊,都是直接吧login_required放上去就可以了,举的例子也都是这样的,这就奇怪了。

问题解答

回答1:

看一下@login_required文档及源码: https://docs.djangoproject.co...

简单提下,@login_required验证是request.user.is_authenticated。官方的例子是应用session会话的,login view时已经将登录信息塞到session中。

回答2:

登录成功后要用django.contrib.auth.login(request, user)把user存入session

标签: Python 编程