假设我有一张表格
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
是否有一种方法为我定义css类在每个字段,这样我就可以使用jQuery基于类在我渲染的页面?
我希望不必手动构建表单。
假设我有一张表格
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
是否有一种方法为我定义css类在每个字段,这样我就可以使用jQuery基于类在我渲染的页面?
我希望不必手动构建表单。
当前回答
下面是在类中声明字段后向小部件添加类定义的另一种解决方案。
def __init__(self, *args, **kwargs):
super(SampleClass, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs['class'] = 'my_class'
其他回答
扩展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'
我觉得这样更干净了。
如果您希望表单中的所有字段都继承某个类,只需定义一个父类,从表单继承。ModelForm,然后继承它
class BaseForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BaseForm, self).__init__(*args, **kwargs)
for field_name, field in self.fields.items():
field.widget.attrs['class'] = 'someClass'
class WhateverForm(BaseForm):
class Meta:
model = SomeModel
这帮助我自动将“form-control”类添加到应用程序的所有表单上的所有字段,而不需要添加代码复制。
你也可以使用Django Crispy Forms,这是一个很好的定义表单的工具,如果你想使用一些CSS框架,比如Bootstrap或Foundation。在这里为表单字段指定类很容易。
你的表单类会是这样的:
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, Field
from crispy_forms.bootstrap import FormActions
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
helper = FormHelper()
helper.form_class = 'your-form-class'
helper.layout = Layout(
Field('name', css_class='name-class'),
Field('age', css_class='age-class'),
Field('django_hacker', css-class='hacker-class'),
FormActions(
Submit('save_changes', 'Save changes'),
)
)
你可以试试这个。
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
name.widget.attrs.update({'class': 'your-class'})
...
你可以在Django Widgets中看到更多信息
要在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类