我有一个表单,希望在字段中设置一些默认值。我使用 View 类的原始解决方案有效
# forms.py
ResultForm(forms.ModelForm):
class Meta:
model = Result
fields = ("date", "club", "goals_for", "goals_against")
...
@staticmethod
def get_initial():
initial = {
'date': datetime.today().date(),
'goals_for': 0,
'goals_against': 0,
}
return initial
和
# views.py
class EnterResultView(View):
template = 'results/enter_result.html'
def get(self, request):
form_class = ResultForm()
form_class.initial = form_class.get_initial()
context = {
'form_class': form_class
}
return render(request, self.template, context)
但是如果我转换为 CreateView 我无法让字段初始化
# views.py
class EnterResultView(CreateView):
template_name = 'results/enter_result.html'
form_class = ResultForm
form_class.initial = form_class.get_initial()
我必须做什么?
[编辑添加模板]
<!-- results/enter_result.html -->
...
{% for field in view.form_class %}
<tr>
<td style="text-align: right">{{ field.label_tag }}</td>
<td>{{ field }}</td>
{% if field.errors %}
{% for error in field.errors %}
<td class="form-error">{{ error }}</td>
{% endfor %}
{% endif %}
</tr>
{% endfor %}
FormMixin
[Django-doc] 的视图有一个 .get_initial()
方法 [Django-doc],因此您可以覆盖它:
class EnterResultView(CreateView):
template_name = 'results/enter_result.html'
form_class = ResultForm
def get_initial(self):
return self.form_class.get_initial()
A
CreateView
构造一个表单并将其作为 form
传递给视图,您不应该使用 view.form_class
,因为这将构造另一个(新)表单,没有任何参数:
{% for field in form %}
…
{% endfor %}
# views.py
class EnterResultView(CreateView):
template_name = 'results/enter_result.html'
form_class = ResultForm
def get_initial(self):
initial = super().initial.copy()
#set initial value of 'bar' in field 'foo'
initial['foo'] = 'bar'
return initial