【问题标题】:Is there a way to override form values in template?有没有办法覆盖模板中的表单值?
【发布时间】:2013-01-05 23:25:09
【问题描述】:

我的forms.py 中有以下内容来定义表单输入的选项:

selection = forms.TypedChoiceField (label="Format", choices = (("Choice1", "Choice1"), ("Choice2", "Choice2"), ("Choice3", "Choice3"),widget = forms.RadioSelect, required= True)

在我的模板中,我目前有以下代码行,允许人们选择这些选项之一。

{{ formtoaddselection.selection }}

一般来说这很好,但我有一个极端情况,有时我想覆盖那些默认选项,例如 CornerCase1CornerCase2

是否可以覆盖模板中的这些默认值,如果可以,如何?

【问题讨论】:

  • 你可以使用一些javascript吗?
  • 为什么要覆盖模板中的值?使用动态选择并将逻辑放在它所属的表单类中:stackoverflow.com/q/3419997/630877
  • 谢谢@arie;..该方法的问题(我认为)是在加载视图/表单时我没有所需的变量...这是在用户之后点击我知道需要填充的选项的特定项目...

标签: django


【解决方案1】:

在模板层中具有非平凡行为的唯一方法是构建template tags.

类似:

@register.simple_tag
def override_form_choices(field, *args, **kwargs):
    field.choices = [(x, x) for x in args]
    return field


{% override_form_choices formtoaddselection.selection 'foo' 'bar' 'baz' %}

您可能会发现在这里分配标签更合适/可读/灵活。

【讨论】:

    猜你喜欢
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 2021-07-25
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    相关资源
    最近更新 更多