【发布时间】: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