djangotemplatesdjango-modelsdjango-templatesdatefield

Show models.DateField value in django template


I have to render the value of models.DateField() in the django template for a countdown functionality. For the DateField I will add the value in the django admin and I need that value in the Front-End. I tried to access the value by writing obj.field(DateField) but it doesn't render the value. Please have a look at the code below, you will understand easily. Any help would be greatly appreciated.

I have a model like this:

class FeaturedProduct(BaseModel):
    type = models.CharField(max_length=255, choices=ProductTypeChoices.choices)
    product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='featured_products')

    daily_deal_countdown = models.DateField(blank=True, null=True)

    class Meta:
        unique_together = ('type', 'product')

    def __str__(self):
        return str(self.product) + '-' + str(self.type)

In the views context I am passing the daily_deals like this:

daily_deal = Product.objects.filter(featured_products__type=ProductTypeChoices.DAILY_DEAL)
context = {'daily_deal':daily_deal}

In the template I am rendering like this:

{% for product in daily_deal  %}
    <div class="daily-deal-countdown" data-countdown-date="{{ product.daily_deal_countdown }}"></div>
{% endfor %}

In the above template the value for the field daily_deal_countdown shows nothing even though my Back-End has the value.

I am using the data-countdown-date value in javasript. And when I am console loging the value it shows nothing.

I also tried to render the value in the element like this:

<div class="daily-deal-countdown">{{ product.daily_deal_countdown }}</div>

But it shows nothing.

Please help me get through.


Solution

  • It looks like you're passing Product objects to your template, while the model which contains daily_deal_countdown is FeaturedProduct. So you have 2 options:

    1. Instead of passing Product into your view you pass FeaturedProduct like daily_deal: FeaturedProduct.objects.filter(type=ProductTypeChoices.DAILY_DEAL)
    2. You have to loop over all featured_products related to each product inside your template