TobaSko
TobaSko

Reputation: 373

Custom tag doesn't render template completely

so here's my custom tag:

@register.inclusion_tag('app/comments_list.html', takes_context=True)
def show_comments(context):
    request = context['request']  
    comments_list = Comments.objects.all().order_by('-comment_time')  
    paginator = Paginator(comments_list, 3) 
    page = request.GET.get('page')  
    try:
        comments = paginator.page(page)   
    except PageNotAnInteger:
        comments = paginator.page(1)  
    except EmptyPage:
        comments = paginator.page(
            paginator.num_pages)  
    return {'comments': comments}

and here's my template to render:

{% for comment in comments %}
{% if comment.commented_by.username == user.username %}
<h6><font color="green">You</font></h6>
{% else %}
{{comment.commented_by}}
<h7>{{ comment.comment_time }}</h7>
{% endif %}
<div class="comment">
    {{comment}}
</div>
{% endfor %}

My model:

class Comments(models.Model):
    commented_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    comment = models.TextField(max_length=300)
    comment_time = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.comment

For some reason it successfully renders everything except for the if condition. And I have no idea why. Any help will be appreciated! Thank you!

Upvotes: 0

Views: 85

Answers (1)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21787

The dictionary you return from your function becomes the context for the template that is going to be rendered. Hence there is no variable user in the context in your template app/comments_list.html. You can change the dictionary you return to also pass the user:

@register.inclusion_tag('app/comments_list.html', takes_context=True)
def show_comments(context):
    ...
    return {'comments': comments, 'user': context['user']}

Note: Generally business logic is performed in the views, and I don't assume many pages need you to get the comments? What you do by adding custom template tags for this would be somewhat frowned upon by Django developers, as this logic is better suited for the view.

Upvotes: 1

Related Questions