问题
When a form in Django has validation errors, the errors are given in a list with class errorlist
.
Elements can be given an error style with Bootstrap by setting class="alert alert-error"
.
What is the best way to combine these, and use Bootstrap's error style for validation errors on Django forms?
回答1:
In Twitter Bootstrap, input elements are enclosed between "control-group"
div
or fieldset
. So I would do something like this in template
{%for field in form %}
<div class="control-group {%if field.errors %}error{%endif%}">
{# render your field #}
</div>
{% endfor %}
Note: In bootstrap, class="alert alert-error"
seems to be for alert messages and not for field specific errors.
回答2:
In Bootstrap 3, input elements are enclosed between "form-group" divs and the error class has changed to has-error.
{%for field in form %}
<div class="form-group {%if field.errors %}has-error{%endif%}">
{# render your field #}
</div>
{% endfor %}
回答3:
It's already been styled! :)
- https://github.com/maraujop/django-crispy-forms/
- https://github.com/earle/django-bootstrap
These libraries act as a wrapper around your form and adds the relevant class names that is used in Django Bootstrap such that you have a base style (bootstrap default) out of the box
回答4:
Bootstrap 4 Django Solution
If <form class="was-validated>"
returns validation in your response, this will work for you:
This example works for the admin/change_form.html
, but it is easy to convert it to your form by changing adminform.form
This will not work for Multi widgets like DateSelectorWidget
delete class="was-validated"
{% if adminform.form.errors %} {# Delete this if you always want active validations #}
<script type="text/javascript">
{% for field in adminform.form %}
var field_input = document.getElementById("{{ field.auto_id }}");
if (field_input) {
field_input.classList.add("is-{% if field.errors %}in{% endif %}valid");
}
{% endfor %}
</script>
{% endif %}
This works for Multi widgets like DateSelectorWidget
but could introduce problems if one field is called start
and the other start_time
Improvements appreciated
{% if adminform.form.errors %} {# Delete this if you always want to see a validation #}
<script type="text/javascript">
{% for field in adminform.form %}
var field_input = document.getElementById("{{ field.auto_id }}");
if (field_input) {
field_input.classList.add("is-{% if field.errors %}in{% endif %}valid");
} else {
multi_widget_fields = document.querySelectorAll('[id^="{{ field.auto_id }}_"]')
multi_widget_fields.forEach(function (element) {
element.classList.add("is-{% if field.errors %}in{% endif %}valid");
});
}
{% endfor %}
</script>
{% endif %}
来源:https://stackoverflow.com/questions/11321767/how-should-i-style-django-validation-errors-with-bootstrap