我在我的Django项目中使用表单,我想指定我在表单中使用的窗口小部件的一些属性,但是我很难弄清楚如何将attrs
字典传递给窗口小部件
view.py :
form_schedule_start = WINDOW_Schedule_Form(section_label=" Start",required=True,initial=scheduleStart,attributes={'class':"form-control",'placeholder':".col-md-4"})
表格:
class WINDOW_Schedule_Form(forms.Form):
def __init__(self,*args,**kwargs):
section_label = kwargs.pop('section_label')
initial_value = kwargs.pop('initial')
required_value = kwargs.pop('required')
attributes = kwargs.pop('attributes')
super(WINDOW_Schedule_Form,self).__init__(*args,**kwargs)
self.fields['WINDOW_Schedule'].label=mark_safe(section_label)
self.fields['WINDOW_Schedule'].initial=initial_value
self.fields['WINDOW_Schedule'].required=required_value
self.fields['WINDOW_Schedule'].attrs=attributes
WINDOW_Schedule = forms.CharField(widget=forms.TextInput())
通常你会这样做
WINDOW_Schedule = forms.CharField(widget=forms.TextInput(attrs={'class':"form-control text-center",'placeholder':".col-md-8"}))
但我希望能够在views.py中指定'class'
和'placeholder'
属性。
我不断收到attributes
未定义的错误。谁能告诉我我做错了什么?
答案 0 :(得分:0)
This Code May Help You Out
class ContactForm(ModelForm):
class Meta:
model = Contact
created = MyDatePicker()
class Uniform(forms):
def __init__(self, *args, **kwargs):
attrs = kwargs.pop("attrs",{})
attrs["class"] = "span3"
kwargs["attrs"] = attrs
super(Uniform, self).__init__(*args, **kwargs)
class MyDatePicker(Uniform,forms.DateInput)
def __init__(self, *args, **kwargs):
attrs = kwargs.pop("attrs",{})
attrs["class"] = "datepick"
attrs["id"] =kwargs.get('datetag', '')
kwargs["attrs"] = attrs
super(MyDatePicker, self).__init__(*args, **kwargs)