Django - check if list contains something in a template

By : JPC

I'm trying to check if an item is in a list (set) inside of a template.

I've found this question here: Is it possible, in a django template, to check if an object is contained in a list

however the solution isn't working for me.

I'm trying this:

{% if trip in request.user.trip_set.all %}

where trip is an instance of a Trip, user is a User, Trip has a ManyToManyField connecting it to User, through TripReservation

class TripReservation(models.Model):
    user = models.ForeignKey(User)
    trip = models.ForeignKey(Trip)

class Trip(models.Model):
    members = models.ManyToManyField(User,blank=True,null=True,through='TripReservation')
By : JPC


request.user.trip_set.all is not a list but a queryset. I think it is the reason of your problem. You can try to change that into a list with the dictsort template filter.

{% if trip in request.user.trip_set.all|dictsort:"id" %}
By : luc

This video can help you solving your question :)
By: admin