Adding css class to field on validation error in django

回眸只為那壹抹淺笑 提交于 2020-01-01 04:21:06

问题


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 what i want is to add a class (error) if there is a validation error to a field.


回答1:


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'



回答2:


Expanding upon errx's answer.

Add the CSS

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

to specifically highlight the field




回答3:


Try this?

self.fields['field_you_want_to_add_error'].widget.attrs['class'] = "error"



回答4:


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
    })


来源:https://stackoverflow.com/questions/4847913/adding-css-class-to-field-on-validation-error-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!