You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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:

1. Refine the 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.

2. Update the 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.

3. Optional: Automatically Delete Expired Notifications

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):

  1. Install Django Q and configure it in your settings.py
  2. Create a tasks.py file 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()
  1. Schedule the task to run daily (via Django Q's admin interface or command line) to keep your database tidy.
4. Display Notifications in the Template

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:18:43