Home > Mobile >  Django template == condition on string doesn't work
Django template == condition on string doesn't work

Time:12-14

I want to display in an email template some conditional informations but even if the {{ error }} confirms the value of my error is list index out of range , the condition is not applied and else is taken in account.

I send to my (email) template this:

views.py

try:
    [...]
except Exception as e:
    error_product_import_alert(
                {'order_increment_id': order_increment_id, 'product': item['sku'], 
                'error': e, 'request': request})

error_product_import_alert()

def error_product_import_alert(context):
    product = context['product']
    order_id = context['order_increment_id']
    error = context['error']
    sujet = f' Anomalie : Import SKU {product} ({order_id}) impossible 
       ({error})!'
    contenu = render_to_string('gsm2/alerts/product_import_ko.html', context)
    [...]

email template

<p>--{{ error }}--</p>
{% if error == 'list index out of range' %}
    <p><strong>Le produit est introuvable dans la base.</strong></p>
{% else %}
    <p><strong>Erreur inconnue : veuillez contacter l'administrateur.</strong></p>
{% endif %}

Maybe my error is so big that I even can't see it. Is there one ?

CodePudding user response:

You are comparing an Exception to a string. This would not work in templates. Try doing the logic in your python function itself and return the error string that will be rendered in the template.

For example:

You should try:

views.py

try:
    [...]
except Exception as e:
    error = "Erreur inconnue : veuillez contacter l'administrateur."
    if e.args[0] == 'list index out of range':
        error = "Le produit est introuvable dans la base."
    error_product_import_alert({
        'order_increment_id': order_increment_id,
        'product': item['sku'], 
        'error': error,
        'request': request
})

template

 <p><strong>{{error}}</strong></p>
  • Related