Home > Software engineering >  Django Framework : Problems with views settings
Django Framework : Problems with views settings

Time:05-16

im learning Django framework and having some issues that i dont get it.
Actually i have apps like Polls/ Blog/ and my homepage/ installed and working as i want.

My problem is to display each data into my homepage_index.html like :
_ how many Question my polls contain
_ how many Article my blog contain

Both of informations are from different apps.

From Django Tutorial i found a solution to display by example my last 3 Question.objects like this.

homepage/views.py :

from django.views import generic
from django.utils import timezone
from polls.models import Question


class homepage(generic.ListView):
    template_name = 'homepage/homepage_index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:3]

my homepage_index.html working :

 {% if latest_question_list %}
     <ul>
        {% for question in latest_question_list %}
            <li><a style="color: white; text-decoration: none;" href="{% url 'polls:detail.html' question.id %}">{{ question.question_text }}</a></li>
        {% endfor %}
     </ul>
{% else %}
     <p>No polls are available.</p>
{% endif %}

How can i define in my homepage/views.py with multiple context_object_name and multiple queryset please ?
I tryied to read many documentations but im still failing

CodePudding user response:

You can find more detail at the offical docs, what you need to do is same as the now value in the demo. https://docs.djangoproject.com/en/4.0/ref/class-based-views/generic-display/#listview

you need to override get_context_data

  1. calculate the number of questions or blogs, or other datas, put them into context
  2. and then render the number at homepage_index.html .

CodePudding user response:

I found a solution without override the get_context_data but i solved half of my problem.( i fail to use the override get_context_data method). Right now i can display multiple informations i wanted in my homepage_index.html like this :

from blog.models import Article
from polls.models import Question

from django.shortcuts import render

def homepage(request):
    list_of_title_article = Article.objects.all()
    list_of_title_question = Question.objects.all()

    return render(request, 'homepage_index.html',  {'latest_question_list': list_of_title_question, 'latest_article_list': list_of_title_article})

It look working as i want but i still dont have any counter method of my objects.

Right now im trying to use Question.objects.all().count() and i have no context to deliver into the render(request, ...)

  • Related