【问题标题】:Django and Jinja2 randomize form fields displayDjango 和 Jinja2 随机化表单字段显示
【发布时间】:2014-11-18 21:11:17
【问题描述】:

我有以下情况:

forms.py

REASONS = [
    {'code': 1, 'reason': 'I want to unsubscribe'},
    {'code': 2, 'reason': 'I hate this site'}]

Myform(forms.Form):
    magic_field = forms.CharField(required=True)

    def __init__(self):
        # Depending on the REASONS list add the fields to the form
        for key in REASONS:
            self.fields['reason_{}'.format(key['code'])] = forms.BooleanField(
                label=_(key['reason']),
                widget=widgets.CheckboxInput())

我想要的是以随机顺序呈现原因的顺序。

template.html

<form method="POST" action="{% url unsubscribe %}">
    {% if some_event %}
        {{ form.magic_field }}
    {% endif %}
    {{ form.reason_1 }} # <-- randomize this order
    {{ form.reason_2 }} # <-- randomize this order
</form>

【问题讨论】:

  • 您是否尝试过在您的 forms.py 中导入 random 然后改组 REASONS ?我不确定这是否会洗牌一次并称之为一个晚上,或者每次出现时都洗牌。
  • @TehTris 是的,问题正如我在下面的高兴回答中所解释的那样
  • 好吧,我明白了。使用 django 本身,您可以创建一个可以应用于它的自定义过滤器(在模板中它最终看起来像 {{ form | filter_name }})除此之外,我能想到的唯一其他方法是如果您使用PHP或Javascript直接将模板中的{{form.reason_1}}{{form.reason_2}}打乱

标签: python django forms jinja2


【解决方案1】:

为什么不先洗牌,然后在模板中使用{% for %} 循环?

类似:

REASONS = [
    {'code': 1, 'reason': 'I want to unsubscribe'},
    {'code': 2, 'reason': 'I hate this site'}]

Myform(forms.Form):
    def __init__(self):
        random.shuffle(REASONS) # use some magic method to shuffle here
        for key in REASONS:
             ...

<form method="POST" action="{% url unsubscribe %}">

    {% for field in form %} #cf https://docs.djangoproject.com/en/dev/topics/forms/#looping-over-the-form-s-fields
        {{ field }}
    {% endfor %}
</form>

希望对你有帮助

编辑 你可以创建一个过滤器或一个函数(我会使用一个函数),比如

{% if some_event %}
    {{ form.magic_field }}
{% endif %}
{% for field in form %}
    {% if is_reason_field(field) %}
        {{ field }}
    {% endif %}
{% endfor %}

在你的 helpers.py 上类似:(我不知道具体是怎么做的)

@register.function
def is_reason_field(field):
    # i'm not sure if field.name exists, you should inspect the field attributes
    return field.name.startswith("reason_"):

嗯,既然我看到了,你可以直接在模板中这样做,因为你使用的是 jinja2

【讨论】:

  • 我知道 random.shuffle() 问题是我的模板无法遍历所有字段,我必须专门调用字段名称,请参阅更新的问题。
猜你喜欢
  • 1970-01-01
  • 2021-11-10
  • 2017-07-29
  • 2020-10-24
  • 1970-01-01
  • 2015-08-20
  • 2019-05-02
  • 1970-01-01
相关资源
最近更新 更多