Beginner
Beginner

Reputation: 2896

Bootstrap dismissable alerts

I have a form in my django project and I want to display the form errors if any when the user clicks submit. This is one of my fields (working on getting one right before I move on to others)

<div class="form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-12" for="title">Title
    </label>

    <div class="col-md-6 col-sm-6 col-xs-12">
        {{ form.title }}
    </div>
    <div class="col-md-3 .col-md-offset-3">
{#                                        <p class="text-danger">{% for error in form.title.errors %}{{ error }}{% endfor %}</p>#}
        <div class="alert alert-warning alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <p>{% for error in form.title.errros %} {{ error }} {% endfor %}</p>
        </div>
</div>

However I have 2 issues :

  1. The alert shows up when the form loads, without the error message:

alert on form load

  1. When I dismiss the alert the form styling gets messed up:

styling messed up

I cant seem to understand what the issue is.

I was able to get the error message without the bootstrap alerts using this code. However it would be great to let the user dismiss an alert after the correction has been made:

<div class="form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-12" for="title">Title
    </label>

    <div class="col-md-6 col-sm-6 col-xs-12">
    {{ form.title }}
    </div>
    <span class="help-block">
        <p class="text-danger">{% for error in form.title.errors %}{{ error }}{% endfor %}</p>
    </span>
</div>

Upvotes: 0

Views: 1548

Answers (1)

rafalmp
rafalmp

Reputation: 4068

Your <div> containing the alert has no closing </div> tag, that messes up the form when you dismiss the alert. As for the alert showing up when the form loads - there's already some content in the alert div (the 'close' button) so it is displayed. You have to render it conditionally (only when there are corresponding errors to show):

    <div class="col-md-3 .col-md-offset-3">
        {% if form.title.errors %}
            <div class="alert alert-warning alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <p>{% for error in form.title.errors %} {{ error }} {% endfor %}</p>
            </div>
        {% endif %}
    </div>

Upvotes: 1

Related Questions