[英]Django - using my context in render_to_response
Is there a way to call all my user data? 有没有办法调用我的所有用户数据? without using all the template variables in my views
无需在我的视图中使用所有模板变量
Templates: 范本:
{% csrf_token %}
<h1>Welcome {{user.full_name}} {{user.last_name}}</h1>
<h1>{{user.email}}</h1>
so in my views I'll use less code, by not declaring all the dict 因此,在我看来,通过不声明所有命令,我将使用更少的代码
views 意见
return render_to_response('user/userhome.html', user)
For django version 1.8 or more you can directly access {{user}} in template. 对于Django 1.8或更高版本,您可以直接在模板中访问{{user}}。 However you can add the following in the TEMPLATE_CONTEXT_PROCESSOR of your settings to access {{user}} directly in the template.
但是,您可以在设置的TEMPLATE_CONTEXT_PROCESSOR中添加以下内容,以直接在模板中访问{{user}}。
'django.contrib.auth.context_processors.auth',
You can use a dict-like object that defines __contains__
and __getitem__
, but uses attribute access to set properties, eg.: 您可以使用类似dict的对象,该对象定义
__contains__
和__getitem__
,但是使用属性访问来设置属性,例如:
from django import shortcuts, template
from django.contrib.auth.decorators import login_required
class Page(dict):
# see http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python
def __init__(self, *args, **kwargs):
super(Page, self).__init__(*args, **kwargs)
self.__dict__ = self
@login_required
def foo(request):
page = Page()
page.user = request.user
return shortcuts.render_to_response('foo.html', page)
then you can write your template exactly the way you would like. 那么您就可以完全按照自己的方式编写模板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.