1

.Hello everyone! I am a beginner in Django and I know that this question was asked hundrets of times on SO, but I still can't get it. I tried to use two models in the same IndexView, but it just repeats the elements which contains in the Petition model.

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

And here is a relevant part of the template:

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

1 Answer 1

4

You're defining your law list in the context as law but then you never reference it, you should be looping over these instead of home_list

{% if law %}
{% for l in law %}  {# law is already defined so cant be used as scope var #}
Sign up to request clarification or add additional context in comments.

3 Comments

What is said is all correct, but also make sure to name your context variables meaningfully, for example "laws" or "law_list" and "petitions" or "petition_list" if you assign querysets to them.
@AidasBendoraitis - I agree, I was trying to keep this simple to avoid changing too many things but descriptive variables are a good idea.
Guys, thank you! I didn't expect that it was so simple

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.