Django Templatetag,请求用户名

时间:2014-04-23 23:40:38

标签: python django django-templates

在模板标签中,我正在使用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>

1 个答案:

答案 0 :(得分:1)

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

@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