我已经在 Stackoverflow 上搜索过这个问题,但找不到答案。
我正在尝试使用清晰的表单和 FormHelper 来渲染 ModelForm,以帮助我很好地布局它。 当我使用 forms.Form 库时,一切工作正常。但现在的主要问题是日期选择器和选择字段不再有带有日期选择器或
的下拉列表这是我的 forms.py 文件:
CITIES= (("London","London"), ("Istanbul","Istanbul"), ("Cape Town","Cape Town"))
class EntryForm(forms.ModelForm):
class Meta:
model = Items
itemName = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'item name'}))
...
date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'}),required=False)
location =forms.ChoiceField(choices=CITIES, required=False)
fields = ['itemName', 'date', 'location']
def __init__(self, *args, **kwargs):
super(EntryForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
'itemName',
...
Row(
Column('date', css_class='form-group col-md-6 mb-0'),
Column('location', css_class='form-group col-md-6 mb-0'),
css_class='form-row'
),
Submit('submit','Submit')
)
我的模板文件如下所示:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<h1>Entry Form</h1>
<br>
{% crispy form %}
<br>
{% endblock %}
不能 100% 确定这是否是问题所在,但我认为您可能只需要将字段转移到 EntryForm 类,如下所示:
class EntryForm(forms.ModelForm):
# Fields should go here, not under the Meta class:
itemName = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'item name'}))
...
date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'}),required=False)
location =forms.ChoiceField(choices=CITIES, required=False)
class Meta:
model = Items
fields = ['itemName', 'date', 'location']