django - 无法将 get_FOO_display 与表单一起使用

标签 django

嗨,我只想在模板中显示表单中选择字段的人类可读文本。问题是模板不显示任何内容。我究竟做错了什么?代码如下。谢谢。

表单.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/

相关文章:

python - 如何在 celery 中安排工作日感知工作

python - 如何使用 Django 创建子类?

python - Django 站点在重新启动或一段时间不活动后加载速度非常慢

django - cx_oracle 6 for Oracle 12C 版本错误

python - 找不到记录器 "myapp.lib"的处理程序

mysql - django IntegrityError : (1048, "Column ' last_login' 不能为空")

django 模块导入错误 - python 2.7 与 python 3.4

django session 不在 iframe 中维护

python - Django 在 100 个对象后停止

python - Django 密码 = models.CharField(_ ('password'), max_length=128)