2013-04-17 31 views
3

我有一个用户视图和日志:Django的user.is_authenticated在视图中的作品,但没有模板

def login_user(request): 
c = {} 
c.update(csrf(request)) 

username = password = '' 
if request.POST: 
    username = request.POST.get('username') 
    password = request.POST.get('password') 

    user = authenticate(username=username, password=password) 
    if user is not None: 
     if user.is_active: 
      login(request, user) 
      c.update(user(request)) 
      return redirect('/module/') 
     else: 
      return redirect('/inactive/') 
    else: 
     return redirect('/failure/') 

return render_to_response('core/auth.html',c) 

这正确登录用户,我可以再访问Django管理页面,如果我在我的超级用户。

登录和被重定向后,我想在屏幕上显示的用户名,目前我使用

  {% if user.is_authenticated %} 
      <p class="navbar-text pull-right">Welcome, {{ user.username }}. Thanks for logging in.</p> 
      {% else %} 
      <p class="navbar-text pull-right">Welcome, new user. Please log in.</p> 
      {% endif %} 

但它似乎总是认为用户没有登录。任何帮助,将不胜感激。

编辑:这是我的模板context处理器

TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth", 
"django.core.context_processors.debug", 
"django.core.context_processors.i18n", 
"django.core.context_processors.media", 
"django.core.context_processors.static", 
"django.core.context_processors.tz", 
"django.contrib.messages.context_processors.messages", 
"django.core.context_processors.request", 
) 
+0

有你得到了什么你' TEMPLATE_CONTEXT_PROCESSORS'?您需要'django.contrib.auth.context_processors.auth'来访问'{{user}}'和/或'django.core.context_processors.request'才能访问'{{request}}'和通过扩展'{{request.user}}')。 – markdsievers

回答

6

您是否尝试发送一个RequestContext对象到您的模板?

return render_to_response('core/auth.html', c, context_instance=RequestContext(request)) 
+0

我已经添加了RequestContext,它给了我错误:全局名称'RequestContext'没有被定义 –

+0

...所以导入它! 'django.template.RequestContext'例如'from django.template import RequestContext' – markdsievers

+4

除非使用RequestContext进行渲染,否则上下文处理器不适用。 Sinc Django 1.3,最好使用['django.shortcuts.render'](https://docs.djangoproject.com/en/1.3/topics/http/shortcuts/#render)而不是['django.shortcuts.render_to_request '](https://docs.djangoproject.com/en/1.3/topics/http/shortcuts/#render-to-response),因为它强制你总是使用一个。 – Dougal

1

我会建议使用快捷功能render()完成您的看法:

这将允许你在request对象传递到模板:

return render(request, 'core/auth.html', c) 
相关问题