如何在Django中为对象设置过期时间?实现高校通知自动下架
Hey there! Let's figure out how to make your Django routine notification app auto-hide notifications after a week. Here's a step-by-step solution tailored to your code:
RoutineOrder Model First, let's tweak your model to add expiration-checking logic and follow Python/PEP8 conventions (like lowercase field names, which is standard practice):
from django.db import models from django.urls import reverse from django.utils import timezone from datetime import timedelta class RoutineOrder(models.Model): subject = models.TextField() # Renamed to lowercase for PEP8 compliance details = RichTextUploadingField() last_edited = models.DateTimeField(auto_now=True) added = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('nitwro:home') @property def is_expired(self): # Check if the notification is older than 7 days return timezone.now() > self.added + timedelta(days=7) class Meta: ordering = ['-added'] # Show newest notifications first
The is_expired property lets you quickly check if a notification should be hidden, and the Meta class ensures notifications are sorted chronologically.
Home View to Filter Active Notifications Modify your view to only pass non-expired notifications to the template. We'll override get_context_data to add the filtered queryset:
from django.views.generic import TemplateView from .models import RoutineOrder from django.utils import timezone from datetime import timedelta class Home(TemplateView): template_name = 'nitwro/home.djt' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Calculate the cutoff date (1 week ago from now) one_week_ago = timezone.now() - timedelta(days=7) # Fetch only notifications added within the last week context['active_notifications'] = RoutineOrder.objects.filter( added__gte=one_week_ago ).order_by('-added') return context
This ensures only valid, non-expired notifications make it to your template.
If you want to clean up old notifications from the database (instead of just hiding them), set up a scheduled task. Here's how to do it with Django Q (a lightweight task queue):
- Install Django Q and configure it in your
settings.py - Create a
tasks.pyfile in your app:
from .models import RoutineOrder from django.utils import timezone from datetime import timedelta def clean_expired_notifications(): """Delete notifications older than 7 days""" one_week_ago = timezone.now() - timedelta(days=7) RoutineOrder.objects.filter(added__lt=one_week_ago).delete()
- Schedule the task to run daily (via Django Q's admin interface or command line) to keep your database tidy.
Update your home.djt template to show the active notifications:
{% for notification in active_notifications %} <div class="notification-card"> <h2>{{ notification.subject }}</h2> <p class="notification-date">Added on: {{ notification.added|date:"F j, Y, g:i a" }}</p> <div class="notification-details">{{ notification.details|safe }}</div> </div> {% empty %} <p>No active routine notifications at this time.</p> {% endfor %}
This will loop through valid notifications, display their content, and show a fallback message if there are none.
内容的提问来源于stack exchange,提问作者Shashwat Shukla

