Question

In a template tag, I'm using request. So in the template, I'm trying to get the logged in user's username using {{ user.username }}. The same code when not used in a template tag but in a view(using request context) works, but now in the template tag it doesn't so it doesn't show the 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>
Was it helpful?

Solution

request is not a variable in that scope. You will have to get it from the context first

@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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top