简体   繁体   中英

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. However you can add the following in the TEMPLATE_CONTEXT_PROCESSOR of your settings to access {{user}} directly in the template.

'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.:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM