user2844523
user2844523

Reputation: 5

Django template variables not working

(I am new to Django)

I'm having a problem with my Django template.

The cruise_details filter should only return one row, but when I try and display this in the template with cruise_details.port for example, nothing is displayed. "code" is correctly getting passed from the URL.

If I remove .port and just put cruise_details I am presented with this on the page

<QuerySet [<Cruise: B724>]>

view.py

def cruise(request, code):

return render(request, 'cruise.html', {
        'cruise_details': Cruise.objects.filter(code=code)
})

cruise.html

{{ cruise_details.port}}

models.py

class Cruise(models.Model):
code = models.CharField(max_length=10)
destination = models.CharField(max_length=60)
url = models.URLField
ship = models.ForeignKey(Ship)
duration = models.IntegerField
start = models.DateField
end = models.DateField
added = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
port = models.CharField(max_length=30)

Upvotes: 0

Views: 1685

Answers (1)

NS0
NS0

Reputation: 6096

The issue is that Cruise.objects.filter(code=code) returns a list, so if there are many possible matches you can modify your template to show them all

{% for cruise_detail in cruise_details %}
    {{ cruise_details.port }}
{% endfor %}

Alternatively, if you know there can only be one result then you can use get instead:

 Cruise.objects.get(code=code)

and your existing template should work.

Hope this helps.

Upvotes: 3

Related Questions