Django表单中的CSS样式

我想样式如下:


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)

contact_form.html:


<form action="" method="post">

  <table>

    {{ form.as_table }}

  </table>

  <input type="submit" value="Submit">

</form>

例如,如何设置一个类或ID为subject,email,message以提供外部样式表到?


繁华开满天机
浏览 922回答 3
3回答

慕无忌1623718

class MyForm(forms.Form):&nbsp; &nbsp; myfield = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myfieldclass'}))要么class MyForm(forms.ModelForm):&nbsp; &nbsp; class Meta:&nbsp; &nbsp; &nbsp; &nbsp; model = MyModel&nbsp; &nbsp; def __init__(self, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; super(MyForm, self).__init__(*args, **kwargs)&nbsp; &nbsp; &nbsp; &nbsp; self.fields['myfield'].widget.attrs.update({'class' : 'myfieldclass'})要么class MyForm(forms.ModelForm):&nbsp; &nbsp; class Meta:&nbsp; &nbsp; &nbsp; &nbsp; model = MyModel&nbsp; &nbsp; &nbsp; &nbsp; widgets = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}),&nbsp; &nbsp; &nbsp; &nbsp; }---编辑---以上是对完成所要求内容的原始问题的代码进行的最简单的更改。如果您在其他地方重复使用表格,还可以避免重复。如果您使用Django的as_table / as_ul / as_p表单方法,则您的类或其他属性将正常工作。如果您需要完全控制以完全自定义渲染,则需要明确记录在案-编辑2 ---添加了更新的方法来为ModelForm指定小部件和属性。
打开App,查看更多内容
随时随地看视频慕课网APP