Django / Python 中的事件自动删除

我在 Django / Python 中有一个事件日历,我试图让它自动不显示基于当前日期已经过去的事件。我正在使用的代码如下所示:


views.py


class HomeView(ListView):

    paginate_by = 1

    model = NewsLetter

    template_name = 'home.html'

    ordering = ['-post_date']


    def events(self):

        return Event.objects.order_by('-event_date')


    def get_context_data(self, **kwargs):

        context = super().get_context_data(**kwargs)

        context['Today'] = timezone.now().date()

        return context

事件.html


{% for event in view.events %}

<div class="py-2">

    {% if event.date <= Today %}

    <ul>

        <li class="font-bold text-gray-900">{{ event.date }}</li>

       <li class="font-medium text-gray-800">{{ event.name }}</li>

        <li class="font-medium text-gray-800">{{ event.description }}</li>

        <strong><p>Location:</p></strong>

        <li class="font-medium text-gray-800">{{ event.location }}</li>

        {% if event.website_url %}

        <a class="font-medium text-gray-800 hover:font-bold hover:text-blue-600" href="{{ event.website_url }}"

            target="blank">Information

        </a>

        {% endif %}

    </ul>

    {% endif %}

</div>

<hr>

{% endfor %}


一只名叫tom的猫
浏览 37回答 1
1回答

森林海

您可以在您的上下文中传递一个值Today,例如基于类的视图:from django.views.generic import ListViewfrom django.utils import timezoneclass MyView(ListView):&nbsp; [...]&nbsp;&nbsp;&nbsp; def get_context_data(self, **kwargs):&nbsp; &nbsp; context = super().get_context_data(**kwargs)&nbsp; &nbsp;&nbsp; &nbsp; context['Today'] = timezone.now().date()&nbsp; &nbsp; return context&nbsp;如果您需要有关向基于类的视图添加额外上下文的详细信息或上下文的简短描述,请参见此处。基于函数的视图的示例:from django.shortcuts import renderfrom django.utils import timezonedef my_view(request):&nbsp; [...your code...]&nbsp;&nbsp;&nbsp; context['Today'] = timezone.now().date()&nbsp; return render(request, template_name="your_template.html",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context=context)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python