假设我有一张表格

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

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

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


当前回答

如果您正在使用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'})

其他回答

如果你想在模板(不是view.py或form.py)的表单字段中添加一个类,比如你想在不覆盖第三方应用程序视图的情况下修改它们,那么在Charlesthk回答中描述的模板过滤器是非常方便的。但是在这个答案中,模板过滤器覆盖了字段可能拥有的任何现有类。

我试图添加这作为一个编辑,但它被建议写作为一个新的答案。

因此,这里有一个模板标签,它尊重字段的现有类:

from django import template

register = template.Library()


@register.filter(name='addclass')
def addclass(field, given_class):
    existing_classes = field.field.widget.attrs.get('class', None)
    if existing_classes:
        if existing_classes.find(given_class) == -1:
            # if the given class doesn't exist in the existing classes
            classes = existing_classes + ' ' + given_class
        else:
            classes = existing_classes
    else:
        classes = given_class
    return field.as_widget(attrs={"class": classes})

扩展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 UserLoginForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(
        attrs={
        'class':'form-control',
        'placeholder':'Username'
        }
    ))
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={
        'class':'form-control',
        'placeholder':'Password'
        }
    ))

还有一个解决方案不需要改变python代码,因此更适合设计师和一次性的表示变化:django-widget-tweak。希望有人会觉得有用。

下面是上面的一个变种,它将给所有字段相同的类(例如jquery漂亮的圆角)。

  # Simple way to assign css class to every field
  def __init__(self, *args, **kwargs):
    super(TranslatedPageForm, self).__init__(*args, **kwargs)
    for myField in self.fields:
      self.fields[myField].widget.attrs['class'] = 'ui-state-default ui-corner-all'