Django - use template tags in if statement [duplicate]
Asked Answered
E

1

10

I saw similar questions but none of them solved my problem .

I have a simple template tag like this :

@register.simple_tag
def liked_by_user(post_id, user):
    try:
        PostModel.objects.get(pk=post_id).like_set.get(user=user)
        return True
    except:
        return False

and i want to use this in an if statement like this :

{% if liked_by_user post.pk request.user %}
        doing somethin...
    {% else %}
        doing somethin...
{% endif %}

what can i do ?

Elongation answered 18/8, 2018 at 13:36 Comment(4)
Return this flag in your post-list queryset.Callaway
@IvanStarostin actually its right , but i want to learn tag filter solutionElongation
Hi Mehdi - is this on a single post page or on a list of posts?Mucoprotein
@MichaelRoberts hi , its a single postElongation
M
23

I would set out your template something like this:

{% liked_by_user "post_id" "request.user" as liked_by_user_flag %}

{% if liked_by_user_flag %} 
   doing somethin...
{% else %} 
   doing somethin...
{% endif %}

However, this intuitively doesn't feel like a template tag sort of situation...but I'm not 100% sure of your use case just yet from your question.

Mucoprotein answered 18/8, 2018 at 14:34 Comment(4)
Should have been liked_by_user_flagMucoprotein
it has template syntax errorElongation
it should be : {% liked_by_user "post_id" "request.user" as liked_by_user_flag %} {% if liked_by_user_flag %} doing somethin... {% else %} doing somethin... {% endif %}Elongation
@Mehdibmp Hi Mehdi - you're quite right, getting my variables mixed up! Apologies, hope the general guidance and solution worked tho.Mucoprotein

© 2022 - 2024 — McMap. All rights reserved.