0

I have an event calendar in Django / Python and I am trying to get it to automatically not show events that have already passed based on the current date. The code I am working with looks like this:

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 %}
LoudEye
  • 27
  • 1
  • 10

1 Answers1

1

You can pass a value for Today in your context, e.g. for a class based view:

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 

See here, if you need for details about adding extra context to class based views or a short description of contexts.

An example for function-based views:

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)
mcrot
  • 446
  • 2
  • 12
  • Would this go in the views? The code I listed above is from the template. – LoudEye Oct 28 '20 at 09:55
  • Yes this is in the view, here for a class-based view. Do you class-based views or functional views? – mcrot Oct 28 '20 at 14:51
  • I've added an example how to pass a context variable when using function-based view. – mcrot Oct 28 '20 at 14:59
  • Yes, this worked. Thank you for your explanation and for providing me with the docs that explain this. Sometimes searching the docs is difficult when you are not sure what to search for. I really appreciate that. – LoudEye Oct 29 '20 at 05:12