Django和Jinja2随机化表单字段显示

时间:2014-11-18 21:11:17

标签: python django forms jinja2

我有以下情况:

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>

1 个答案:

答案 0 :(得分: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