简体   繁体   English

如何指定表单中字段的顺序? [django-脆皮形式]

[英]How do I specify the order of fields in a form? [django-crispy-forms]

We are using Django 2.1 for Speedy Net .我们将 Django 2.1 用于Speedy Net We have a contact form and recently it has been used by spammers to send us spam.我们有一个联系表格,最近垃圾邮件发送者使用它向我们发送垃圾邮件。 I decided to add a "no_bots" field to the form where I'm trying to prevent bots from submitting the form successfully.我决定在我试图阻止机器人成功提交表单的表单中添加一个“no_bots”字段。 I checked the form and it works, but the problem is we have 2 sites - on one site (Speedy Net) the order of the fields is correct, and on the other site (Speedy Match) the order of the fields is not correct - the "no_bots" field comes before the "message" field but I want it to be the last field.我检查了表单并且它有效,但问题是我们有 2 个站点 - 在一个站点 (Speedy Net) 上,字段的顺序是正确的,而在另一个站点 (Speedy Match) 上,字段的顺序不正确 - “no_bots”字段出现在“message”字段之前,但我希望它是最后一个字段。 How do I make it last?我如何让它持久? Our template tag contains just {% crispy form %} and I defined the order of the fields in class Meta :我们的模板标签只包含{% crispy form %}并且我在class Meta定义了字段的顺序:

class FeedbackForm(ModelFormWithDefaults):
    ...
    no_bots = forms.CharField(label=_('Type the number "17"'), required=True)

    class Meta:
        model = Feedback
        fields = ('sender_name', 'sender_email', 'text', 'no_bots')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelperWithDefaults()
        if (self.defaults.get('sender')):
            del self.fields['sender_name']
            del self.fields['sender_email']
            del self.fields['no_bots']
            self.helper.add_input(Submit('submit', pgettext_lazy(context=self.defaults['sender'].get_gender(), message='Send')))
        else:
            self.fields['sender_name'].required = True
            self.fields['sender_email'].required = True
            self.helper.add_layout(Row(
                Div('sender_name', css_class='col-md-6'),
                Div('sender_email', css_class='col-md-6'),
            ))
            self.helper.add_input(Submit('submit', _('Send')))

    def clean_text(self):
        text = self.cleaned_data.get('text')
        for not_allowed_string in self._not_allowed_strings:
            if (not_allowed_string in text):
                raise ValidationError(_("Please contact us by e-mail."))
        return text

    def clean_no_bots(self):
        no_bots = self.cleaned_data.get('no_bots')
        if (not (no_bots == "17")):
            raise ValidationError(_("Not 17."))
        return no_bots

快速网 快速匹配

By the way, I checked our staging server, and there it's the opposite - the order of fields is correct in Speedy Match but not correct in Speedy Net.顺便说一下,我检查了我们的临时服务器,结果正好相反 - Speedy Match 中的字段顺序是正确的,但 Speedy Net 中的字段顺序不正确。 This is weird because they both use the same code!这很奇怪,因为它们都使用相同的代码! I think it means that the order of the fields is random.我认为这意味着字段的顺序是随机的。

Update: I deleted all the *.pyc files on the production server, and now the order of fields is correct in both sites.更新:我删除了生产服务器上的所有 *.pyc 文件,现在两个站点中的字段顺序都是正确的。 I also deleted these files on the staging server, and now the order of the fields is not correct in both sites.我还在临时服务器上删除了这些文件,现在两个站点中的字段顺序都不正确。 I did it again on the staging server and the order of the fields changed again in one of the sites.我在登台服务器上再次执行此操作,其中一个站点中的字段顺序再次更改。

The cause: iterating over an unordered collection原因:迭代无序集合

crispy_forms 's FormHelper.render_layout does this: crispy_formsFormHelper.render_layout这样做:

fields = set(form.fields.keys())
left_fields_to_render = fields - form.rendered_fields
for field in left_fields_to_render:
    ...

At this point, left_fields_to_render is a set : {'text', 'no_bots'}此时, left_fields_to_render是一个set{'text', 'no_bots'}

A set is an unordered collection. set是一个无序的集合。

This sometimes returns False : [a for a in {'text', 'no_bots'}] == ['text', 'no_bots']这有时会返回False[a for a in {'text', 'no_bots'}] == ['text', 'no_bots']

You can try this by opening several different instances of the Python interpreter — I noticed that it's usually consistent within an instance of a Python interpreter.您可以通过打开 Python 解释器的几个不同实例来尝试此操作——我注意到它在 Python 解释器的实例中通常是一致的。

The fix: iterate over a list解决方法:遍历一个列表

Basically:基本上:

fields = tuple(form.fields.keys())
left_fields_to_render = list_difference(fields, form.rendered_fields)
for field in left_fields_to_render:
    ...

I have submitted a PR for a more complete fix at django-crispy-forms/django-crispy-forms#952 .我已经在django-crispy-forms/django-crispy-forms#952提交了一个 PR 以获得更完整的修复。

The workaround: explicitly specify the fields in the layout解决方法:明确指定布局中的字段

Arguably, the intended usage of layout if you don't set render_unmentioned_fields = True .可以说,如果您不设置render_unmentioned_fields = True ,则布局的预期用途。

You already call self.helper.add_layout for two of the four fields;您已经为四个字段中的两个调用了self.helper.add_layout you can just go all the way:你可以一路走下去:

self.helper.add_layout(MultiWidgetField(
    Row(
        Div('sender_name', css_class='col-md-6'),
        Div('sender_email', css_class='col-md-6'),
    ),
    'text',
    'no_bots',
))

Did you tried to use the Layout method?您是否尝试过使用 Layout 方法?

From the documentation:从文档:

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit

class ExampleForm(forms.Form):
    [...]
    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Fieldset(
                'first arg is the legend of the fieldset',
                'like_website',
                'favorite_number',
                'favorite_color',
                'favorite_food',
                'notes'
            ),
            ButtonHolder(
                Submit('submit', 'Submit', css_class='button white')
            )

https://django-crispy-forms.readthedocs.io/en/latest/layouts.html#fundamentals https://django-crispy-forms.readthedocs.io/en/latest/layouts.html#fundamentals

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM