簡體   English   中英

Django Templatetag,請求用戶名

[英]Django Templatetag, request username

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM