2011-05-06 47 views
0

我正在创建用户登录并更改链接登录注销Django模板检查用户已通过身份验证并且存在

的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> 

但在输入的网址上,我没有看到Sigin链接,但我得到了登出。 当我将{% if user %}更改为{% if not user %}时,可以看到Signin。

请让我知道我错了

回答

0

的错误是没有了,以后我清除浏览器的历史,也settings.py中添加SESSION_EXPIRE_AT_BROWSER_CLOSE = True 。在syncdb之后重新启动Django服务器。 工作

0

user总是正确的。您必须致电is_authenticated()方法。

{% if user.is_authenticated %} 
+0

@Ignacio现在我确实显示了登录链接。但是,当用户登录时,它不会改变注册。:( – 2011-05-06 13:29:54

+0

而且我不会为django的默认登录。我选择自定义,其中我将继续跟踪会话以保持跟踪 – 2011-05-06 13:35:21

+0

What for for ?http://docs.djangoproject.com/zh-cn/dev/topics/auth/#writing-an-authentication-backend – 2011-05-06 13:37:24

相关问题