【问题标题】:Events auto delete in Django / PythonDjango / Python中的事件自动删除
【发布时间】:2021-02-10 13:13:34
【问题描述】:

我在 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

events.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 %}

【问题讨论】:

    标签: python django


    【解决方案1】:

    您可以在上下文中为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 
    

    如果您需要有关向基于类的视图添加额外上下文的详细信息,请参阅hereshort description of contexts

    基于函数的视图示例:

    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)
    

    【讨论】:

    • 这会出现在视图中吗?我上面列出的代码来自模板。
    • 是的,这是在视图中,这里是基于类的视图。你是基于类的视图还是功能视图?
    • 我添加了一个示例,如何在使用基于函数的视图时传递上下文变量。
    • 是的,这行得通。感谢您的解释,并为我提供了解释这一点的文档。当您不确定要搜索什么时,有时搜索文档很困难。我真的很感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多