Reputation: 1943
I have a simple pet app.
The app display all the pet stores and when you click on the pet store . You will get to see all the pet names, picture .
The problem is after I created the first pet and other pets . The template doesn't update the new pets . So , it only display the first pet.
So when I delete the first pet . It displays Page not found (404) even though . I added new pets to the store.
I tried to use a for loop inside the template but it display an error that I can't iterate over it and A friend told me not to use for loop when you are rendering only single data.
How Can I display more pets at a store?
I think the problem is at my animal.html also my views.py
my animal.html
{% if pet %}
<li>Pet = {{ pet.animal }}</li>
<li>description = {{pet.description}} </li>
<img src="{{ pet.image.url }}">
{% endif %}
my store.html
Sydney's Pet Store
{% if store %}
<ul>
{% for a in store %}
<li><a href ="{% url world:brazil a.id %}">{{ a.name }}</li>
{% endfor %}
</ul>
{% endif %}
My views.py
from pet.models import Store , Pet
from django.shortcuts import render_to_response ,get_object_or_404
def index(request):
store = Store.objects.all()
return render_to_response ('store.html',{'store':store})
def brazil(request , animal_id):
pet = get_object_or_404(Pet, pk=animal_id)
return render_to_response ('animal.html',{'pet':pet})
My models.py
from django.db import models
class Store(models.Model):
name = models.CharField(max_length = 20)
number = models.BigIntegerField()
address =models.CharField(max_length = 20)
def __unicode__(self):
return self.name
class Pet(models.Model):
animal = models.CharField(max_length =20)
description = models.TextField()
owner = models.ForeignKey(Store)
image = models.FileField(upload_to="images/")
def __unicode__(self):
return self.animal
Upvotes: 2
Views: 4163
Reputation: 13308
Create a queryset in your view (something like) -
def brazil(request , animal_id):
pets = Pet.objects.all()
return render_to_response ('animal.html',{'pets':pets})
Then iterate it in your template -
{% for pet in pets %}
<li>Pet = {{ pet.animal }}</li>
<li>description = {{pet.description}} </li>
<img src="{{ pet.image.url }}">
{% endfor %}
Have a look at the queryset docs to get more idea of how to pass the objects you want to your templates
Upvotes: 1
Reputation: 22808
If you want to show more than 1 data, you must use filter not get_object_or_404. You will use get_object_or_404 if you want to show only 1 data.
def brazil(request , owner_id):
pets = Pet.objects.filter(owner_id=owner_id)
return render_to_response ('animal.html',{'pets':pets})
{% if pets %}
<ul>
{% for pet in pets %}
<li>
Pet = {{ pet.animal }}<br/>
description = {{pet.description}}<br/>
<img src="{{ pet.image.url }}">
</li>
{% endfor %}
</ul>
{% endif %}
Upvotes: 3