【问题标题】:calculate remaining days in python/Django在 python/Django 中计算剩余天数
【发布时间】:2021-06-11 14:02:30
【问题描述】:

我正在创建一个 Django 电子商务网站;该网站“销售”数字商品。 在其中一个与“用户配置文件”相关的模板上,我正在尝试计算 Web 应用程序中的剩余天数,但到目前为止还没有成功地将其显示在我的模板上。 我尝试创建一个剩余天数函数,但目前无法使用它

代码如下:

models.py

class UserSubscription(models.Model):
    user = models.ForeignKey(User, related_name= 'tosubscriptions', on_delete=models.CASCADE, null=True, blank=True)
    subscription = models.ForeignKey("Subscription", related_name = 'tosubscriptions',on_delete=models.CASCADE, null=True, blank=True) 
    # startdate of a subscription, auto_now_add needs to be "False" for acummulation of days in subscriptions
    start_date = models.DateTimeField(auto_now_add=False, null=True, blank=True,verbose_name="Start Date") 
    expiry_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True,verbose_name="Expiry Date") # expiry date of a subscription
    # "is_canceled" is used to calculate if a usersubscription is active
    is_canceled = models.BooleanField(default=False, verbose_name="Is Canceled")
    cancel_date = models.DateTimeField(auto_now=False, auto_now_add=False, blank=True, null=True)


    class Meta:
        verbose_name = "User Subscription"
        verbose_name_plural = "User Subscriptions"

    def __str__(self):
        """Unicode representation of UserSubscription"""

        return "PK: [{}] Subscription of: {}, {}, Expiring the: {}, is canceled: {}".format(
                str(self.pk),
                str(self.user),
                str(self.subscription),
                str(self.expiry_date),
                str(self.is_canceled )
            )
    
    def save(self, *args, **kwargs):  # calculated when object is saved and saved in the db
        """
        Function to calculate the expiry date of a user subscription. 
        The expiry_date is saved in the db
        """
        self.expiry_date = self.start_date + timedelta(self.subscription.duration)  # "timedelta" added to be able to calculate automaticaly end dates of subscriptions
        super().save()

    @property
    def is_active(self):
        """
        Function to calculate if a subscription is active 
        This calculation is not stocked in the db
        """
        if not self.is_canceled and datetime.datetime.today() < self.expiry_date:
            return True
        else:
            return False

    @property
    def remaining_days(self):
        remaining = self.expiry_date - self.datetime.datetime.today()
        return remaining

class Subscription(models.Model):
    plan_name = models.CharField(max_length=50, null=True, blank=True, verbose_name="Subscription Plan Name")    
    description = models.TextField(verbose_name="Subscription Plan Description")   
    price = models.FloatField(verbose_name="Subscription Plan Price")   
    start_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True, verbose_name="Subscription Plan Start Date")
    end_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True, verbose_name="Subscription Plan End Date")   
    is_active = models.BooleanField(default=True)
    duration = models.IntegerField(blank=True, null=True)    

    class Meta:
        verbose_name = "Subscription"
        verbose_name_plural = "Subscriptions"       

    def __str__(self):
        """Unicode representation of Subscription"""

        return " Subscription type: {}, Description: {}, Price: {}, Is active: {}".format(
                self.plan_name,
                self.description,
                self.price,
                self.is_active
            )

views.py

@login_required
def user_profile(request):
    """"""

    all_user_subscription = UserSubscription.objects.filter(user=request.user)
    last_user_subscription = all_user_subscription.last()

    context = {
        "all_user_subscription": all_user_subscription,
        "last_user_subscription": last_user_subscription,
    }

    return render(request, "myprofile.html",context)

模板

<p>My Current Plan: {{last_user_subscription.subscription.plan_name}}</p>
<p>End Date: {{last_user_subscription.expiry_date}}</p>
<p>remaining days {{last_user_subscription.remaining}}</p>
<a href="{% url 'home' %}">Renew my Subscription</a>
<hr>
<p>My Bills:</p>
{%for i in all_user_subscription%}
<p>Bill : {{ i.subscription.price }} €</p>
<p>Bought on the : {{ i.start_date }} </p>
{% endfor %}
<hr>

结果:

My Current Plan: 1 Month

End Date: April 12, 2021, 11:22 p.m.

remaining days

Renew my Subscription

My Bills:

Bill : 5.0 €

Bought on : March 13, 2021, 10:22 p.m. 

【问题讨论】:

    标签: django django-views django-templates


    【解决方案1】:

    我不明白到底是什么问题。但是你的'def剩余天数':

    1. self.datetime.datetime.today() 更改为 datetime.datetime.today()
    2. 当您减去 datetimes 对象时,您会得到 timedelta 对象

    我想它可以帮助你:

    @property
    def remaining_days(self):
            remaining = (self.expiry_date - datetime.datetime.today()).days
            return remaining
    

    更新: 我试图用你的模型写数据,除了save() 方法(我不喜欢它,我刚刚删除它)和这个(我把它放在 Meta 之前)

        @property
        def remaining_days(self):
            remaining = (datetime.datetime.now().date() - self.expiry_date.date()).days
            return remaining
    

    得到了这个(我创建了随机日期,expary_date = 2020-10-14)

    >>> u=UserSubscription.objects.all().first()
    >>> u.remaining_days
    151
    

    我想这就是你想要的

    【讨论】:

    • 抱歉不清楚。我期望的结果是以整数格式获得剩余天数。
    • 我上面的代码返回int格式。我想我可以帮助你
    • 谢谢。我尝试了上面的代码,但不知何故我仍然无法得到结果。 remaining = (self.expiry_date - datetime.datetime.today()).days 在模板上我尝试了以下操作:&lt;p&gt;remaining days {{all_user_subscription.remaining}}&lt;/p&gt; 但我在模板方面仍然一无所获。有什么想法吗?
    • 谢谢科科。它起作用了,但我不得不研究这个link。由于我导入了“从日期时间导入日期时间”,因此我不得不使用“datetime.now().date()”而不是“datetime.datetime.now().date”(根据您的建议)。如果我导入了“import datetime”(我想这就是你模拟的方式),你的代码就会起作用。问题解决了:-)
    【解决方案2】:

    尝试在 ide 中使用调试器运行代码,并在 return 语句之前添加断点。 我同意 koko 的观点,要么将模型中的 DateTimeFields 更改为 DateField(我建议这样做,因为我看不到任何地方都在使用时间)或将日期时间转换为日期,然后进行计算。

    【讨论】:

      猜你喜欢
      • 2014-06-11
      • 2021-08-12
      • 2013-06-26
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2021-02-18
      相关资源
      最近更新 更多