Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django – what is wrong with my If statement?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 class="d-flex flex-column mt-4">
    <a class="btn btn-outline-secondary btn-sm" 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'}),
                }

>Solution :

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

HTML

{% if product.category == 4 %}
<div class="d-flex flex-column mt-4"> 
<a class="btn btn-outline-secondary btn-sm" href="{% url 'ElderFlowerReview' product.id %}">Tasting Notes</a> 
</div> 
{% endif %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading