[英]django forms: styling widget when field is required or has an error
I'm creating a django form and I can't seem to access each field's widget to style it differently when there's an error or when the field is required (eg: highlight the field's box). 我正在创建一个django表单,当出现错误或需要该字段时,我似乎无法访问每个字段的小部件以不同的方式设置其样式(例如:突出显示该字段的框)。
HTML: HTML:
{% block content %}
<form action="" method="POST" class="form"> {% csrf_token %}
{% for field in form %}
<div class="fields-container">
<p class="label">{{ field.label }}</p>
{{ field }}
</div>
{{ field.errors }}
{% endfor %}
<button type="submit" id="form-button">Submit</button>
</form>
{% endblock %}
CSS: CSS:
.label {
margin: 0 5px 0 0;
width: 20%;
text-align: left;
}
#id_full_name, #id_email, #id_message {
margin: 0;
flex: 1 1;
}
#id_message {
resize: none;
overflow: auto;
}
.errorlist { /*default css class for form errors*/
color: 999999;
font-size: 75%;
font-weight: bold;
list-style: none;
margin-bottom: 5px;
align-self: flex-start;
}
I've been accessing and styling the widgets using #id_fieldname, but I've tried the following and it didn't work: 我一直在使用#id_fieldname访问和设置窗口小部件的样式,但是我尝试了以下操作,但没有成功:
#id_fieldname.required, id_fieldname.error { border: 2px solid red; }
Thanks in advance! 提前致谢!
You could add a class 'required' in your container <div>
: 您可以在容器<div>
添加“必需”类:
<div class="fields-container {% if field.field.required %}required{% endif %}">
Using django form methods form.as_p
, form.as_ul
, form.as_table
, this would be done automatically if you declare a specific css class for required fields in your Form, for example: 使用Django表单方法form.as_p
, form.as_ul
, form.as_table
,如果您为Form中的必填字段声明了特定的CSS类, form.as_table
自动完成此操作,例如:
class myForm(forms.Form):
required_css_class = 'required'
...
More in documentation 更多文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.