为了账号安全,请及时绑定邮箱和手机立即绑定

Django / Python 中的事件自动删除

Django / Python 中的事件自动删除

一只名叫tom的猫 2024-01-16 10:22:41
我在 Django / Python 中有一个事件日历,我试图让它自动不显示基于当前日期已经过去的事件。我正在使用的代码如下所示:views.pyclass 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 %}
查看完整描述

1 回答

?
森林海

TA贡献2011条经验 获得超2个赞

您可以在您的上下文中传递一个值Today,例如基于类的视图:


from django.views.generic import ListView

from django.utils import timezone


class MyView(ListView):


  [...]

  

  def get_context_data(self, **kwargs):

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

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

    return context 

如果您需要有关向基于类的视图添加额外上下文的详细信息或上下文的简短描述,请参见此处。


基于函数的视图的示例:


from django.shortcuts import render

from django.utils import timezone


def my_view(request):

  [...your code...]

  

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


  return render(request, template_name="your_template.html",

                context=context)


查看完整回答
反对 回复 2024-01-16
  • 1 回答
  • 0 关注
  • 34 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信