How to Style Django Validation Errors with Bootstrap

How should I style Django validation errors with Bootstrap?

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.

How to modify Bootstrap 4 form validation information presentation in Django?

Did you tried debugging in the template ?

I did something like you want to achieve :

<form method="post"> {% csrf_token %}
{% for field in form %}
<div class="form-group">
{{ field }}
<label class="control-label" for="{{ field.id_for_label }}">{{ field.label }}</label>
{% if field.errors %}
<div class="border-bottom-danger">
{{ field.errors }}
</div>
{% endif %}
</div>
{% endfor %}
<button class="btn btn-block" type="submit">Submit</button>
</form>

Where :

  1. {{ field }} is the input, where you are correctly adding visible.field.widget.attrs['class'] = 'form-control'
  2. Then, errors you want (I guess) are stored in the field, so you could get its with {{ field.errors }} if it has some.

The difference between your code and mine is that I'm using field.errors instead if field.help_text, I hope it can help.

I suggest you to put breakpoint in your template, then analyze your form object. Then you can do whatever you want in your frontend.

  1. If no error : Add class outline-green to your input wrapper (the <div class="row")
  2. If error : Display the error within a div underneath your input

PS : If you want to outline the input, and not the row wrapper, you can do it through css (or better with Sass if you are using it):

.row.outline-green > input{
border: 1px solid green;
}
<div class="row outline-green">
{{ field }}
</div>

Django: How to update a class attribute of an invalid form field to display error messages in Bootstrap 5?

I don't know correct way but this way I've done my job

if form.is_valid():
form.save()
return redirect("success")
else:
for field in form.errors:
form[field].field.widget.attrs['class'] += ' is-invalid'

this will add is-invalid class to all invalid fields

Note: don't forget to add space ' is-invalid'

Can't give css class to django error message

1)first thing is error_css_class must be outside of meta not the inside of meta class

2)and the second thing is in django error always come as a unordered list so do one thing put error_css_class = "error" in proper place on the for and add css like this so it might work for you

.error li {
font-size: 1rem;
margin-left: 20px;
}

Style Django form error message

Check the class name in the source code browser.
You can try to change the class name like that:

class MyForm(forms.Form):
error_css_class = "error"


Related Topics



Leave a reply



Submit