【问题标题】:Django Templatetag, request usernameDjango Templatetag,请求用户名
【发布时间】:2014-04-23 23:40:38
【问题描述】:

在模板标签中,我使用request。所以在模板中,我尝试使用{{ user.username }} 获取登录用户的用户名。相同的代码在模板标签中不使用但在视图中(使用请求上下文)可以工作,但现在在模板标签中它没有,所以它不显示用户名。

student_block.py(templatetag)

# template tag
def student_block(request):
    progress = 20
    user_id = request.user.id
    first_name = request.user.first_name
    last_name = request.user.last_name

    try:
        studying_course = Student.objects.get(user__id=user_id).course
        studying_year = Student.objects.get(user__id=user_id).year
    except Student.DoesNotExist:
        studying_course = None
        studying_year = None


    if first_name and last_name:
        progress += 30
    if (studying_year and studying_course):
        progress += 50
    return {'progress': progress, 'course': studying_course, 'year': studying_year}

register.inclusion_tag('studies/student_block.html')(student_block)

student_block.html

<!-- Student Block Start -->
<div class="panel panel-default sidebar">
    <div class="panel-heading">
        <h3 class="panel-title">Hey, {{ user.username }}</h3>
    </div>
</div>

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    request 不是该范围内的变量。您必须先从上下文中获取它

    @register.inclusion_tag('studies/student_block.html', takes_context = True)
    def student_block(context):
        request = context['request']
        # you can use request what ever you want
    

    https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags

    【讨论】:

      猜你喜欢
      • 2011-08-18
      • 2020-07-13
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多