Im trying to raise error for empty fields or fields which are not validating in form so Im doing this method below but I know this is not the best way...
views.py :
'KnowledgeForm': form,
'errors': str(form.errors),
but then in Django-template I have to use if
for each field and im adding custom name for each field , i dont know why i cant use Verbose_name...
Template :
{% if errors %}
<div >
<p>
{% if KnowledgeForm.errors.KnowledgeTitle %}
عنوان دانش: {{ KnowledgeForm.errors.KnowledgeTitle }}
{% endif %}
{% if KnowledgeForm.errors.KnowledgeTextSummary %}
Summary: {{ KnowledgeForm.errors.KnowledgeTextSummary }}
{% endif %}
{% if KnowledgeForm.errors.KnowledgeFromDate %}
from Date: {{ KnowledgeForm.errors.KnowledgeFromDate }}
{% endif %}
{% if KnowledgeForm.errors.KnowledgetoDate %}
To date : {{ KnowledgeForm.errors.KnowledgetoDate }}
{% endif %}
{% if KnowledgeForm.errors.KnowledgeProcess %}
Chart: {{ KnowledgeForm.errors.KnowledgeProcess }}
{% endif %}
{% endif %}
</p>
</div>
{% endif %}
Second method :
{% if KnowledgeForm.errors %}
<ul >
{% for key,value in KnowledgeForm.errors.items %}
<li>{{ key|escape }} : {{ value|escape }}</li>
{% endfor %}
</ul>
{% endif %}
in this method i get the name based on whats used in models.py how can i change it?
CodePudding user response:
The most clear and concise way is to use a forloop
Try replacing your entire if
block in your HTML with the below code
{% for field in KnowledgeForm %}
{% if field.errors %}
<div >
{{ field.label_tag }} {{ field.errors }}
</div>
{% endf %}
{% endfor %}
I don't think you need 'errors': str(form.errors),
CodePudding user response:
It is because you convert errors to str and you don't need to separate this.
In your template:
# if you want to use verbose_name just use label_tag.
# label_tag is equal to your verbose name.
{% for field in KnowledgeForm %}
<div >
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endfor %}
So you have the error top of input