2016-02-02 35 views
1

。大家好!我是Django的初學者,我知道這個問題被問及時間問題,但我仍然無法得到它。我試圖在同一個IndexView中使用兩個模型,但它只是重複了請求模型中包含的元素。單個視圖中的多個模型(Django,python)

class IndexView(generic.ListView): 
    template_name = 'home.html' 
    context_object_name = 'home_list' 
    model = Petition 

    def get_context_data(self, **kwargs): 
     context = super(IndexView, self).get_context_data(**kwargs) 
     context['petition'] = Petition.objects.all() 
     context['law'] = Law.objects.all() 

     return context 

這裏是模板的相關部分:

{% if home_list %} 
    <ul> 
    {% for petition in home_list%} 
     <li><a href="/petitions/{{ petition.id }}/">{{ petition.question }}</a></li> 



     <img src="{{ petition.image.url }}" height="200" width="300"> 

    {% endfor %} 
    </ul> 
{% else %} 
    <p>No petitions are available.</p> 
{% endif %} 


{% if home_list %} 
    <ul> 
    {% for law in home_list %} 
     <li><a href="/laws/{{ law.id }}/">{{ law.question }}</a></li> 



     <img src="{{ law.image.url }}" height="200" width="300"> 

    {% endfor %} 
    </ul> 
{% else %} 
    <p>No laws are available.</p> 
{% endif %} 

回答

4

你定義你law列表的背景下,作爲法律,但你永遠不引用它,你應該遍歷這些替代的home_list

{% if law %} 
{% for l in law %} {# law is already defined so cant be used as scope var #} 
+1

還說什麼是正確的,但也一定要有意義命名上下文變量,例如「法律」或「law_list」和「上訪」或「PE tition_list「,如果你給他們分配查詢集。 –

+0

@AidasBendoraitis - 我同意,我試圖保持這種簡單,以避免改變太多的東西,但描述性變量是一個好主意。 – Sayse

+1

夥計們,謝謝!我沒有想到它那麼簡單 – Vasile