2016-02-02 44 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