假设我有一张表格

class SampleClass(forms.Form):
    name = forms.CharField(max_length=30)
    age = forms.IntegerField()
    django_hacker = forms.BooleanField(required=False)

是否有一种方法为我定义css类在每个字段,这样我就可以使用jQuery基于类在我渲染的页面?

我希望不必手动构建表单。


当前回答

你可以在这里获得各种输入字段的样式选项

小部件是Django对HTML输入元素的表示。小部件处理HTML的呈现,以及从与小部件对应的GET/POST字典中提取数据。

email = forms.EmailField(label='Your email', widget=forms.EmailInput(attrs={'class': 'ui segment teal'}))

其他回答

如果您正在使用ModelForm,并且已经包含了带有fields属性的必要字段,那么有一种方法可以为它们定义css类。对我来说,这比“for循环”方法更好,因为我想为不同的输入字段使用不同类型的css类。

fields = ( 'date', 'title'),
widgets = {'date': forms.DateInput(attrs={'class': 'datepicker'}),
          'title': forms.TextInput(attrs={'class': 'title'})}

或者您也可以尝试通过Form类的构造函数设置它们

def __init__(self, *args, **kwargs):
       super().__init__(*args, **kwargs)
       self.fields['date'].widget.attrs.update({'class': 'datepicker'})
       self.fields['title'].widget.attrs.update({'class':'title'})

要在django中定义css类,只需在表单中使用小部件即可。

例子:

class ProcessForm(forms.ModelForm):  
    class Meta:  
        model = Processmachine 
        fields = ['machine_name', 'operation_no', 'process_uploadfile'] #https://docs.djangoproject.com/en/3.0/ref/forms/widgets/
        widgets = { 'machine_name': forms.TextInput(attrs={ 'class': 'form-control' }), 
            'operation_no': forms.TextInput(attrs={ 'class': 'form-control' }),
            'process_uploadfile': forms.ClearableFileInput(attrs={ 'class': 'form-control' }),
      }

在上面的表单中,我在attrs中使用了css类

扩展docs.djangoproject.com中指出的方法:

class MyForm(forms.Form): 
    comment = forms.CharField(
            widget=forms.TextInput(attrs={'size':'40'}))

我认为必须知道每个字段的本机小部件类型很麻烦,而且为了在表单字段上放一个类名而重写默认值也很有趣。这似乎对我很管用:

class MyForm(forms.Form): 
    #This instantiates the field w/ the default widget
    comment = forms.CharField()

    #We only override the part we care about
    comment.widget.attrs['size'] = '40'

我觉得这样更干净了。

你可以试试这个。

class SampleClass(forms.Form):
  name = forms.CharField(max_length=30)
  name.widget.attrs.update({'class': 'your-class'})
...

你可以在Django Widgets中看到更多信息

回答我自己的问题。叹息

http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs

我没有意识到它被传递到小部件构造函数中。