如何在base.html中获取用户价值? [英] How to get user value in base.html?

查看:135
本文介绍了如何在base.html中获取用户价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用main base.html中的用户数据,这是我的主要模板。

I'd like to work with user data in main base.html which is my main template.

我实际上使用登录通用视图。当我在主页上登录时,它会提供用户信息,但在所有其他页面中用户为空白。

I actually use the login generic view. When I'm logged in on the homepage it gives me user information but in all other pages user is blank.

我已经阅读了许多关于这个的内容:请求 RequestContext ,我添加了 django.contrib.auth.context_processors.auth 到处理器列表。

I've read many things about this: request, RequestContext, I've added django.contrib.auth.context_processors.auth to the processors list.

任何想法如何让这个变量显示无处不在? >

Any idea how to get this variable to show everywhere?

推荐答案

两种方式:

如果您使用django 1.4+,可以使用 render()从您的视图返回:

If you're using django 1.4+, you can use, render() when returning from your views:

def my_view(request):
    ...
return render(request, 'template.html', ctx)

如果你使用旧的django或者你不喜欢渲染方法,您将使用 render_to_response ,如下所示:

If you're using older django or you don't like the render approach, you would return RequestContext using render_to_response, like this:

def my_view(request):
   ...
return render_to_response('template.html', ctx, context_instance=RequestContext(request))

编辑:抱歉,忘了实际回答问题。如果您使用上述方法之一呈现模板,并且具有以下功能:

sorry, forgot to actually answer question. If you're rendering your templates using one of the above ways and have:

  • django.contrib.auth in your INSTALLED_APPS
  • auth in midleware
  • auth in context_processors (take a look at default settings.py file: https://github.com/django/django/blob/master/django/conf/global_settings.py )

然后,您可以使用{{user}}和{{user.is_anonymous}}来了解发生了什么。

Then you can use: {{ user }} and {{ user.is_anonymous }} to figure out what's going on.

这篇关于如何在base.html中获取用户价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆