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

Python Django和Jinja2随机化表单字段显示,python,django,forms,jinja2,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

我有以下情况:

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>

{%如果某个_事件%}
{{form.magic_field}}
{%endif%}

{{form.reason_1}}{p>为什么不先洗牌原因,然后在模板中使用
{%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>
在你的助手上。py类似:(我不知道具体怎么做)


嗯,现在我看到了,您可以直接在模板中执行此操作,因为您使用的是jinja2

您是否尝试在forms.py上导入
random
,然后洗牌
REASONS
?我不确定这会不会把它洗一次,然后叫它一个晚上,或者每次它出现的时候都洗一次。@TehTris是的,问题是我在下面的“请不要回答”中解释的好吧,我明白了。使用django本身,您可能能够创建一个可以应用于它的自定义过滤器(在模板中,它最终看起来像
{form | filter_name}}
),除此之外,我唯一能想到的另一种方法是使用PHP或Javascript来洗牌
{form.reason_1}
{form reason_2}
直接在模板中我知道random.shuffle()问题是我的模板无法迭代所有字段,我必须明确地调用字段名,请参见更新的问题。
{% if some_event %}
    {{ form.magic_field }}
{% endif %}
{% for field in form %}
    {% if is_reason_field(field) %}
        {{ field }}
    {% endif %}
{% endfor %}
@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_"):