嗨,我只想在模板中显示表单中选择字段的人类可读文本。问题是模板不显示任何内容。我究竟做错了什么?代码如下。谢谢。
表单.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)")
View .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 }}
最佳答案
您必须在模型字段上使用 get_operation_display
https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display
您似乎正在尝试在表单的 cleaned_data
字典上使用它
我认为表单字段不存在 get_FOO_display
方法
这个答案详细介绍了一个自定义模板过滤器,它将为您提供表单字段当前所选选项的“显示”值:
https://stackoverflow.com/a/1108875/202168
关于django - 无法将 get_FOO_display 与表单一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21109462/