2013-03-03 22 views
2

我有一個簡單的寵物應用程序。Django No Pet與給定的查詢匹配

該應用程序顯示所有的寵物商店,你點擊寵物商店時。你會看到所有的寵物名稱,圖片。

問題是我創建的第一個寵物等寵物後。該模板不會更新新的寵物。所以,它只顯示第一隻寵物。

所以當我刪除第一個寵物。儘管如此,它仍然顯示找不到頁面(404)。我給商店添加了新的寵物。

我試圖用的模板內循環,但它顯示的是我不能迭代它的錯誤,一個朋友告訴我,不要當你只呈現單個數據用於循環。

如何顯示在商店更多的寵物嗎?

我認爲這個問題是在我的animal.html也是我views.py

我animal.html

{% if pet %} 
<li>Pet = {{ pet.animal }}</li> 
<li>description = {{pet.description}} </li> 

<img src="{{ pet.image.url }}"> 
{% endif %} 

我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 %} 

我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}) 

我莫dels.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 

回答

2

如果你想展示多個數據,你必須使用過濾器不get_object_or_404。 如果您只想顯示1個數據,您將使用get_object_or_404。

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 %} 
+0

你會用我的situatio一個ManyToManyField或一個ForeignKey N + – donkeyboy72 2013-03-03 11:36:30

+0

店鋪 – catherine 2013-03-03 11:41:52

+0

擁有者的外鍵,當你點擊你想要顯示該店內寵物列表的商店時,對吧? – catherine 2013-03-03 11:42:23

1

創建您的視圖的查詢集(像) -

def brazil(request , animal_id): 
    pets = Pet.objects.all() 
    return render_to_response ('animal.html',{'pets':pets}) 

然後重複它在你的模板 -

{% for pet in pets %} 
<li>Pet = {{ pet.animal }}</li> 
<li>description = {{pet.description}} </li> 
<img src="{{ pet.image.url }}"> 
{% endfor %} 

看一看在queryset docs獲得更多的想法如何你想要的對象傳遞給你的模板

+0

好吧,我現在就這樣做。謝謝 – donkeyboy72 2013-03-03 11:45:00