Django:事件发生后将帖子离线

时间:2019-05-28 07:24:47

标签: django python-3.x django-models django-templates django-2.2

我正在尝试将某个事件(确定日期)后的帖子下线。我已经开发了一个用于测试目标的简单模型,并且在模型内部放置了一个函数(名为is_expired ),该函数理想地必须定义帖子是否在线。下面是模型

from django.db import models
from django.utils import timezone
import datetime

class BlogPost(models.Model):
    CHOICHES = (
        ("Unselected", "Unselected"),
        ("One Month", "One Month"),
        ("One Year", "One Year"),
        )

    title = models.CharField(
        max_length=70,
        unique=True,
        )
    membership = models.CharField(
        max_length=50,
        choices=CHOICHES,
        default="Unselected",
        )
    publishing_date = models.DateTimeField(
                        default=timezone.now,
                        )

    def __str__(self):
        return self.title

    @property
    def is_future(self):
        if self.publishing_date > datetime.datetime.now():
            return True
        return False

    @property
    def is_expired(self):
        if self.membership == "One Month":
            def monthly(self):
                if publishing_date + datetime.timedelta(days=30) <= datetime.datetime.now():
                    return True
        if self.membership == "One Year":
            def yearly(self):
                if publishing_date + datetime.timedelta(days=365) <= datetime.datetime.now():
                    return True
        return False

    class Meta:
        ordering = ['-publishing_date']

为了显示所有过期帖子的列表,我使用了这个简单的模板

{% for p in posts_list %}
  {% if p.is_future or p.is_expired %}
  <div class="container my-4 bg-primary">
    <h3><a class="text-white" href="{{ p.get_absolute_url }}">{{ p.title }}</a></h3>
    <h5>Data di pubblicazione: {{ p.publishing_date|date:"d - M - Y | G:i:s" }}</h5>
    {% if p.is_expired %}
      <p>Expired? <span class="text-danger"><strong>Yes</strong></span></p>
    {% else %}
      <p>Expired? <span class="text-success"><strong>No</strong></span></p>
    {% endif %}
  </div>
  {% endif %}
{% empty %}
  <div class="container my-4 bg-primary">
    <h1>No posts!</h1>
  </div>
{% endfor %}

问题是我看不到过期的帖子,而只看到将来的帖子(功能为is_future 的将来的帖子),控制台内没有错误,所以我现在不在哪里错误。 我是Python和Django的新手。

有人可以向我指出错误吗?

更新:

views.py

def listPosts(request):
    posts_list = BlogPost.objects.all()
    context = {"posts_list": posts_list}
    template = 'blog/reading/list_post.html'
    return render(request, template, context)

1 个答案:

答案 0 :(得分:1)

您的is_expired()方法始终返回False。在方法内部,您定义了两个内部函数(monthlyyearly),但是从不调用它们。您想要的那些内部函数实际上是无用的:

@property
def is_expired(self):
    if self.membership == "One Month":
        if self.publishing_date + datetime.timedelta(days=30) >= datetime.datetime.now():
            return True
    elif self.membership == "One Year":
        if self.publishing_date + datetime.timedelta(days=365) >= datetime.datetime.now():
            return True
    return False