Myzel394
Myzel394

Reputation: 1317

Django Check for user in list

I'm creating a django blog app where users can add comments to articles. I want to remove the post button when the user has already commented.

I have a model named article and another one named comment (with ForeignKey to article)

I tried {% if any request.user in article.comment_set.all} but that doesn't work. I tried to loop over article.comment_set.all but that didn't work either.

Is there a method to do this in the template?

Upvotes: 0

Views: 394

Answers (1)

ruddra
ruddra

Reputation: 51948

Rather than doing that in template, why don't you do that in view and send it via context. For example:

def view(request):
    ...
    user_exists = article.comment_set.filter(user=request.user).exists()
    context = {}
    context['user_exists'] = user_exists
    return render(request, 'template.html', context)

in template:

{% if user_exists %}

// do something

{% else %}

// do something else

{% endif %}

Upvotes: 1

Related Questions