【问题标题】:Django Template Check user is authenticated and is presentDjango 模板检查用户已通过身份验证并且存在
【发布时间】:2011-05-06 13:18:16
【问题描述】:

我正在创建用户登录并将 signin 的链接更改为 signout。

我的views.py是:

#This index is for my landing page i.e.first.html where I have Sigin link which needs to hidden on Successful
def index(request):
    if 'username' not in request.session :
        return render_to_response('gharnivas/ghar.html', context_instance=RequestContext(request))
    else:
    u = request.session['username']
    return render_to_response('gharnivas/ghar.html',{ 'user' : u },context_instance=RequestContext(request))


#This here, is the view for my check the user and create required
def ulogin(request):
    if request.method != 'POST':
        raise Http404('Only POSTs are allowed')
    try:
        m = Personal.objects.get(name__icontains=request.POST['username'])
        if m.password == request.POST['password']:
            request.session['username'] = m.id
            return HttpResponseRedirect('/')
    except Personal.DoesNotExist:
        return render_to_response('gharnivas/signin.html', {'error' : True }, context_instance=RequestContext(request))

urls.py 是:

urlpatterns = patterns('',
    url(r'^$', 'gharnivas.views.index'),#landing page
    url(r'^signin/$','gharnivas.views.signin'),#The view for sign In page
    url(r'^ulogin/$','gharnivas.views.ulogin'),#The view for creating a change in user login
}

然后在登陆页面,即 first.html 我有这个代码:

<table>
  <tr>
    <td>
    {% if user %}
            <div class="whitecolor"  >
                    &nbsp;&nbsp;<a href="">SignOut</a>&nbsp;&nbsp;&nbsp;</div>
    {% else %}
            <a href="/signin/">SignIn</a>&nbsp;&nbsp;&nbsp;
    {% endif %}
        </td>       
    <td><a href="/register/">Register</a>&nbsp;&nbsp;&nbsp;</td>
    <td><a href="/"> Home </a></td>
  </tr>
<table>

但是在输入的 url 上,我看不到 Sigin Link ,但我得到了 Signout。 当我将{% if user %} 更改为{% if not user %} 时,就会看到登录。

请告诉我哪里出错了

【问题讨论】:

    标签: django authentication django-templates django-views


    【解决方案1】:

    在我清除浏览器历史记录并添加SESSION_EXPIRE_AT_BROWSER_CLOSE = True后,错误不再存在 在 settings.py 中。在 syncdb 之后重新启动了 Django 服务器。 工作过

    【讨论】:

      【解决方案2】:

      user 始终为真。您必须调用is_authenticated() 方法。

      {% if user.is_authenticated %}
      

      【讨论】:

      • @Ignacio 现在我确实显示了登录链接。但是当用户实际登录时,它不会更改 Signout。:(
      • 我不会使用 django 的默认登录名。我正在选择自定义,其中我将继续进行会话以跟踪
      • 我想尝试自定义会话。但是疑问仍然存在,因为if 语句怎么会不起作用?我什至将user 更改为另一个变量cu 左右。 !! :|
      • 如果您使用的是完全自定义的身份验证方法,那么您必须使用该身份验证方法使用的任何内容来指示用户是否经过身份验证。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      相关资源
      最近更新 更多