Home > database >  When I access the page, nothing appears
When I access the page, nothing appears

Time:11-02

I want to use the following code to filter the data in models.py in views.py and output the Today_list to today.html, but when I open this url, nothing is displayed. What is the problem?

    class Post(models.Model): 
        created =models.DateTimeField(auto_now_add=True,editable=False,blank=False,null=False)
        title =models.CharField(max_length=255,blank=False,null=False)
        body =models.TextField(blank=True,null=False)
        def __str__(self):
            return self.title

views.py

    from Todolist import models
    from django.views.generic import ListView
    from django.utils import timezone

    class TodayView(ListView):
        model = models.Post
        template_name ='Todolist/today.html'
        def get_queryset(self):
            Today_list= models.Post.objects.filter(
                created=timezone.now()).order_by('-id')
            return Today_list

todaylist.html

    {% extends "Todolist/base.html" %}
    {% block content %}
    {% for item in Today_list %}
    <tr>
        <td>{{item.title}}</td>
    </tr>
    {% endfor %}
    {% endblock %}

urls.py

    urlpatterns=[
        path('today/' ,views.TodayView.as_view() ,name='today')]

CodePudding user response:

use get_context_data to add Today_list to context ref : https://docs.djangoproject.com/en/4.1/ref/class-based-views/generic-display/

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['Today_list'] = self.get_queryset()
    return context

or you can simply use in template model.name_list in your case it will be post_list instead of today_list

{% extends "Todolist/base.html" %}
{% block content %}
{% for item in post_list %}
<tr>
    <td>{{item.title}}</td>
</tr>
{% endfor %}
{% endblock %}

CodePudding user response:

problem is where you want objects that created today, but your filter check just right now, not today. So for achieve today's posts, you can do the this filtering:

from django.utils import timezone

def get_queryset(self):
    Today_list = models.Post.objects.filter(
        created__gte=timezone.now().replace(hour=0, minute=0, second=0),
        created__lte=timezone.now().replace(hour=23, minute=59, second=59)
    ).order_by('-id')
    return Today_list

this queryset returns objects that have been created today.

  • Related