计算python/Django中的剩余天数

时间:2021-03-13 21:38:01

标签: django django-views django-templates

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

代码如下:

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. 

2 个答案:

答案 0 :(得分:0)

我不明白究竟是什么问题。但是你的“def剩余天数”:

  1. self.datetime.datetime.today() 更改为 datetime.datetime.today()
  2. 当您减去日期时间对象时,您会得到 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

我认为这是你想要的

答案 1 :(得分:0)

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