首页 > 解决方案 > strftime 模型对象并在 html 模板中显示

问题描述

美好的一天,我想对创建的模型实例进行 strftime 并将其显示在 HTML 模板中(作为 transaction_id)。但我似乎没有做对。谢谢你的帮助。

模型.py

class Order(models.Model):
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField()
    address = models.CharField(max_length=250)
    phone_number = models.CharField(max_length=20)
    city = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    paid = models.BooleanField(default=False)
    braintree_id = models.CharField(max_length=150, blank=True)
    coupon = models.ForeignKey(Coupon, related_name='orders', null=True, blank=True, on_delete=models.SET_NULL)
    discount = models.IntegerField(default=0, validators=[
        MinValueValidator(0),
        MaxValueValidator(100)
    ])

视图.py

def order_list(request):#datetime.now().strftime("%Y%m%d%H%M%S")
    transaction_id = Order.objects.get(created)
    orders = Order.objects.all()
    current_user = request.user
    success = Order.objects.filter(user=current_user.id).filter(paid=True)
    fail = Order.objects.filter(user=current_user.id).filter(paid=False)
    return render(request, 'orders/order/order_list.html', {
        'success': success,
        'fail': fail,
        'current_user': current_user,
        'orders':orders,
        'transaction_id':transaction_id,
    })

html

<p class="card-text">
<mark style="color: whitesmoke; background-color: brown;border-radius: 3px;font-weight: bold;">{{transaction_id}}</mark>
</p>

标签: python-3.xdjangostrftime

解决方案


好吧,这就是我为解决这个问题所做的,我在我的 models.py 中添加了 strftime 函数

模型.py

    def htmldisplaytime(self):
        time = self.created.strftime("%Y%m%d%H%M%S")
        return time

推荐阅读