Шаблон Django == условие на строке не работает
Я хочу отобразить в шаблоне электронной почты некоторые условные данные, но даже если {{ error }}
подтверждает значение моей ошибки индекс списка вне диапазона , условие не применяется и else
принимается во внимание.
Я отправляю на свой (email) шаблон следующее:
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)
[...]
шаблон электронной почты
<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 %}
Возможно, моя ошибка настолько велика, что я даже не могу ее увидеть. Есть ли она?
Вы сравниваете Exception
со строкой. Это не будет работать в шаблонах. Попробуйте выполнить логику в самой функции python и вернуть строку ошибки, которая будет отображена в шаблоне.
Например:
Вам следует попробовать:
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>