Xon*_*nal 29 authentication django
对不起,如果您在我之前提出此问题时尝试过帮助我.不得不删除该问题,因为出于某种原因我不被允许编辑其他信息.
我正在我的django网站上实现用户身份验证.一切正常.我的观点,模型,网址等都已设置完毕.用户可以注册,登录,注销.我遇到的问题是这段代码:
{% if request.user.is_authenticated %}
<li><a href="/logout">Log Out</a></li>
{% else %}
<li><a href="/login">Log In</a></li>
{% endif %}
Run Code Online (Sandbox Code Playgroud)
即使我已登录,它仍然显示"登录"作为选项而不是"注销".但是,如果我点击链接,它会将我重定向到/ profile,因为如果我已经登录,那就是视图告诉它要做的事情.所以,显然它知道我已登录,但模板不是readint user.is_authenticated为true.
与登录请求相关的视图是:
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
profile = authenticate(username=username, password=password)
if profile is not None:
login(request, profile)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('template/login.html', {'form': form}, context_instance=RequestContext(request))
else:
return render_to_response('template/login.html', {'form': form}, context_instance=RequestContext(request))
else:
''' user is not submitting the form, show them login form '''
form = LoginForm()
context = {'form': form}
return render_to_response('template/login.html', context, context_instance = RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
Ala*_*air 45
如果启用了auth上下文处理器,那么user它已经在模板上下文中,您可以执行以下操作:
{% if user.is_authenticated %}
Run Code Online (Sandbox Code Playgroud)
如果要request在模板中访问,请确保已启用请求上下文处理器.
在您提出的问题中render_to_response.从Django 1.3开始,最好用render而不是render_to_response.使用render_to_response与RequestContext(request)在Django <= 1.9的作品,但是从Django的1.10起,你必须使用render,如果你想上下文处理器一起工作的捷径.
return render(request, 'template/login.html', context)
Run Code Online (Sandbox Code Playgroud)
要知道,自从Django的1.10的is_authenticated装饰有@property和它的行为不同.
对于UNAUTHENTICATED用户调用{{user.is_authenticated}}结果:
CallableBool(True)(在Django <1.10时True)
对于AUTHENTICATED用户调用{{user.is_authenticated}}结果:
CallableBool(False)(在Django <1.10时False)
如果您需要将例如传递给您的javascript值,true或者false您可以通过应用过滤器来执行此操作|yesno:"true,false"
<script language="javascript">
var DJANGO_USER = "{{user.is_authenticated|yesno:"true,false"}}";
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33774 次 |
| 最近记录: |