Django和Jinja2随机显示表单字段

2024-04-27 04:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下情况:

表单.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())

我想要的是把原因按随机顺序排列。在

模板.html

^{pr2}$

Tags: thetokeypyself表单fields情况
1条回答
网友
1楼 · 发布于 2024-04-27 04:21:39

为什么不先把原因混在一起,然后在模板中使用{% 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>

希望这有帮助

编辑 你可以创建一个过滤器或者一个函数,比如

^{pr2}$

在你的助手.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

相关问题 更多 >