Django 1.4 - {{ request.user.username}} doesn't render in template

后端 未结 2 1767
伪装坚强ぢ
伪装坚强ぢ 2020-12-30 10:32

In my view, I can print request.user.username, however in the template, {{request.user.username}} does not appear. To make this easy, I removed the logic from the function,

相关标签:
2条回答
  • 2020-12-30 10:42

    As mentioned in the documentation, authenticated user's object is stored within user variable in templates. Mentioned documentation includes the following example:

    When rendering a template RequestContext, the currently logged-in user, either a User instance or an AnonymousUser instance, is stored in the template variable {{ user }}:

    {% if user.is_authenticated %}
        <p>Welcome, {{ user.get_username }}. Thanks for logging in.</p>
    {% else %}
        <p>Welcome, new user. Please log in.</p>
    {% endif %}
    

    EDIT: Thanks to @buffer, who dug out this old answer, I have updated it with most recent state. When it was originally written, in less than a month after Django 1.4 (which was released at the end of March 2012), it was correct. But since Django 1.5, proper method to get username is to call get_username() on user model instance. This has been added due to ability to swap User class (and have custom field as username).

    0 讨论(0)
  • 2020-12-30 10:55

    Check out the documentation for RequestContext and TEMPLATE_CONTEXT_PROCESSORS.

    If you want request to be in your template context, then you need to include django.core.context_processors.request in your TEMPLATE_CONTEXT_PROCESSORS setting. It is not there by default.

    However as Tadeck pointed out in his answer user is already available if you are using the default settings, since django.contrib.auth.context_processors.auth is part of the default list for TEMPLATE_CONTEXT_PROCESSORS.

    0 讨论(0)
提交回复
热议问题