skip to Main Content

I’m trying to code a form with fields that, if a user inputs data that doesn’t pass the validation of the form, change their background colors from the default white to lightcoral.

Here is a fragment of the HTML file that contains the form itself:

 <div id="div_formbox">
        <form method="post" id="form_appointments">
            {% csrf_token %}
            
            {{ form.non_field_errors }}
                          
            <div class="input_group">
                
                <div class="input_field {% if form.name.errors %}error{% endif %}">
                    {{ form.name}}
                </div>
                
                <div class="input_field {% if form.last_name.errors %}error{% endif %}">
                    {{ form.last_name }}
                </div>
                                              
                
                <div class="input_field {% if form.email.errors %}error{% endif %}">
                    {{ form.email }}
                </div>
                               
       
            </div>
    
            <button type="submit">Send</button>
        </form>
    </div>

And here is the part of the CSS file where I try to apply the color change to the input fields with errors:

.error {
   background-color: lightcoral;
}

As you can see, I’m using Django tags to change the class of the form fields with errors from "input_field" to "error".
Next, in the CSS file, I reference the "error" class to apply the styling I want. But it doesn’t work. I’ve tried a bunch of variations but none have worked. I’m out of ideas.

3

Answers


  1. Maybe try like below.

    .error {
       background-color: lightcoral !important;
    }
    
    Login or Signup to reply.
  2. Open developer tools in your browser and check if the CSS file is loaded, the class name, and the properties of the element in styles section below the Element tab, make sure that everything is actually in its desired form. It may be that the css file was not correctly.

    What is the type of the form argument passed in your view function?
    form.name.errors is a little confusing since form must be a model and name is a property (maybe a CharField), but still you access error property of the field which is not mentioned in Docs as a standard built-in option.

    Login or Signup to reply.
  3. I think you need to mention the JavaScript events on which color should get change. Like on submit or on mouseover something like that. Because here form is not when to change color.

    Hope this find helpful.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search