Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - check if list contains something in a template

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')
like image 550
JPC Avatar asked Feb 03 '11 02:02

JPC


1 Answers

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" %}
like image 91
luc Avatar answered Nov 09 '22 00:11

luc