Adding css class to field on validation error in django

前端 未结 5 1104
谎友^
谎友^ 2021-01-01 18:40

I am using Django\'s modelform and its really good. How can I highlight the actual text box (e.g. border:red ) if there is a validation error associated with it. Basically

相关标签:
5条回答
  • 2021-01-01 19:19

    template :

    <div style="color:red">{{ userForm.short_description.errors.as_text  }}</div>
    
    0 讨论(0)
  • 2021-01-01 19:22

    To answer the original question.

    You can add the desired class to the field in the view to where you are submitting your form and doing your form.is_valid() check. Not the prettiest but it will work.

    def submit_form(request):
        if request.method = 'POST':
            if. form.is_valid():
                # Do something with clean form data
                pass
            else:
                # Append css class to every field that contains errors.
                for field in form.errors:
                    form[field].field.widget.attrs['class'] += ' my-css-class'
        return render(request, submit_form.html, {
            'form': form
        })
    
    0 讨论(0)
  • 2021-01-01 19:31

    Try this?

    self.fields['field_you_want_to_add_error'].widget.attrs['class'] = "error"
    
    0 讨论(0)
  • 2021-01-01 19:33

    What about defining error_css_class? http://docs.djangoproject.com/en/dev/ref/forms/api/#styling-required-or-erroneous-form-rows?

    class MyForm(ModelForm):
        error_css_class = 'error'
    
    0 讨论(0)
  • 2021-01-01 19:36

    Expanding upon errx's answer.

    Add the CSS

    .error input, .error select {
        border: 2px red solid;
    }
    

    to specifically highlight the field

    0 讨论(0)
提交回复
热议问题