Home > Enterprise >  Django - what is wrong with my If statement?
Django - what is wrong with my If statement?

Time:07-16

I inserted an if statement in my template - I only want the form to appear if the product category is "Champagne".

For some reason, the product does not appear for champagne products.

Here is the code

Models.py

CATEGORY=(
    (1,'Rum'),
    (2,'Gin'),
    (3,'Whisky'),
    (4,'Champagne'),
    (5,'Others'),
    )

class Product(models.Model):
    name = models.CharField('Product Name', max_length=120, null=True)
    category = models.IntegerField(choices=CATEGORY, default=0)
    description = models.TextField(blank=True, null=True)
    price = models.DecimalField(null=True, max_digits=6, decimal_places=3)
    image_url= models.URLField('Image Web Address', blank=True)
    product_url = models.URLField('Product Web Address', blank=True)
    class Meta:
        db_table='Product'
    def __str__(self):
        return str(self.name)

HTML

{% if product.category == 'Champagne' %}
<div >
    <a  href="{% url 'ElderFlowerReview' product.id %}">Tasting Notes</a>
</div>
{% endif %}

Forms.py

class DrinkForm(ModelForm):
    class Meta:
        model = Product
        fields = ('name','category', 'description')
        labels ={
            'name': '',
            'category': '',
            'description': '',
        }

        widgets = {
                    'name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter name'}),
                    'category': forms.Select(attrs={'class':'form-control', 'placeholder':'Enter category'}),
                    'description':forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter description'}),
                }

CodePudding user response:

You have to use 4 insted of "Champagne" 4 is value and "Champagne" is label

HTML

{% if product.category == 4 %}
<div > 
<a  href="{% url 'ElderFlowerReview' product.id %}">Tasting Notes</a> 
</div> 
{% endif %}
  • Related