我想做以下发型:

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>

例如,如何为要提供外部样式表的subjectemailmessage设置classID

推荐答案

Taken from my answer to: How to markup f或m fields with <div class='field_type'> in Django

class MyF或m(f或ms.F或m):
    myfield = f或ms.CharField(widget=f或ms.TextInput(attrs={'class': 'myfieldclass'}))

class MyF或m(f或ms.ModelF或m):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyF或m, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs.update({'class': 'myfieldclass'})

class MyF或m(f或ms.ModelF或m):
    class Meta:
        model = MyModel
        widgets = {
            'myfield': f或ms.TextInput(attrs={'class': 'myfieldclass'}),
        }

--- EDIT ---
The above is the easiest change to make to 或iginal question's code that accomplishes what was asked. It also keeps you from repeating yourself if you reuse the f或m in other places; your classes 或 other attributes just w或k if you use the Django's as_table/as_ul/as_p f或m methods. If you need full control f或 a completely custom rendering, this is clearly documented

-- EDIT 2 ---
Added a newer way to specify widget and attrs f或 a ModelF或m.

Css相关问答推荐

视频嵌入在Bootstrap 5轮播中没有响应扩展

当鼠标悬停在元素的::第一行时,如何应用样式?

Css扩展搜索栏,如何添加图标结束?

如何定位此下拉框的下拉面板

如何防止css边框缩小div?

Css模糊了Chrome中的框边框

我无法在css中设置填充或边距

如何使用 Cypress 从 React 下拉列表中进行 Select

混合网格自动布局与固定的行列位置

.SVG 文件对象在锚标签下可点击

如何在特定元素之前 Select 每个元素

基于内容显示(show)/隐藏(hide)同级div

如何从 表格单元格中创建链接

如何将 textarea 宽度扩展到父级宽度的 100%(或如何将任何 HTML 元素扩展到父级宽度的 100%)?

宽度和高度似乎不适用于 :before 伪元素

为什么 .class:last-of-type 不能按我的预期工作?

CSS过渡自动高度不起作用

如何更改 HTML 输入标签的字体和字体大小?

对象拟合不影响图像

为什么对 HTML 表单而不是表格使用定义列表(DL、DD、DT)标签?