Django表单中的CSS样式 [英] CSS styling in Django forms
问题描述
如何调整以下样式:
在forms.py中 -
in forms.py --
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
email = forms.EmailField(required=False)
message = forms.CharField(widget=forms.Textarea)
.html -
in contact_form.html --
<form action="" method="post">
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
例如,如何设置主题,电子邮件,外部样式表?谢谢
For example, how do I set a class or ID for the subject, email, message to provide an external style sheet to? Thank you
推荐答案
class MyForm(forms.Form):
myfield = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myfieldclass'}))
>
or
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myfield'].widget.attrs.update({'class' : 'myfieldclass'})
或
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
widgets = {
'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}),
}
--- EDIT ---
上面是对原始问题的代码进行最简单的修改,以完成所提出的问题。如果您在其他地方重复使用此表单,它也会阻止您重复自己;你的类或其他属性只是工作,如果你使用Django的as_table / as_ul / as_p形式的方法。如果您需要完全控制完全自定义呈现,则这是清楚记录的< a>
--- EDIT ---
The above is the easiest change to make to original question's code that accomplishes what was asked. It also keeps you from repeating yourself if you reuse the form in other places; your classes or other attributes just work if you use the Django's as_table/as_ul/as_p form methods. If you need full control for a completely custom rendering, this is clearly documented
- EDIT 2 ---
添加了更新的方式来指定ModelForm的窗口小部件和attrs。
-- EDIT 2 ---
Added a newer way to specify widget and attrs for a ModelForm.
这篇关于Django表单中的CSS样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!