您好我只想在模板中显示表单中选择字段的人类可读文本。问题是模板没有显示任何内容。我究竟做错了什么?代码如下。感谢。
forms.py
class MathsForm(forms.Form):
operation_choices = [
(0, None),
(1, 'Addition'),
(2, 'Subtration'),
(3, 'Times'),
(4, 'Division')
]
operation = forms.ChoiceField(choices=operation_choices, help_text="(required)")
views.py
def maths(request):
if request.method == 'POST':
form = MathsForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
return render(request, 'maths/test.html', {'cd': cd})
else:
form = MathsForm(
initial={'operation': 1}
)
return render(request, 'maths/maths.html', {'form': form})
模板 - maths.html
{{ cd.get_operation_display }}
答案 0 :(得分:3)
您必须在模型字段上使用get_operation_display
https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display
您似乎正在尝试在表单的cleaned_data
字典中使用它
我不认为表单字段存在get_FOO_display
方法
此SO答案详细说明了一个自定义模板过滤器,它将为您提供表单字段当前所选选项的“显示”值:
https://stackoverflow.com/a/1108875/202168
答案 1 :(得分:0)
您可以在views.py中传递选定的操作:
,而不是将已清理的数据作为cd传递def maths(request):
if request.method == 'POST':
form = MathsForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
op_dict = dict(form.fields['operation'].choices)
op = op_dict[int(cd['operation'])]
return render(request, 'maths/test.html', {'op': op})
else:
form = MathsForm(
initial={'operation': 1}
)
return render(request, 'maths/maths.html', {'form': form})