django – 从表单字段输入中清除额外空格的位置?

栏目: Python · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/8320739/django-where-to-clean-extra-whitespace-from-form-field-inputs

我刚刚发现Django不会自动从表单字段输入中删除额外的空格,我想我理解其基本原理(‘框架不应该改变用户输入’).

我想我知道如何使用 python 的re删除多余的空格:

#data = re.sub('\A\s+|\s+\Z', '', data)
data = data.strip()
data = re.sub('\s+', ' ', data)

问题是我应该在哪里这样做?据推测,这应该发生在一个形式的清洁阶段,但哪一个?理想情况下,我想清理所有额外空格的字段.如果它应该在clean_field()方法中完成,这意味着我必须有很多clean_field()方法基本上做同样的事情,这似乎是很多重复.

如果不是表单的清理阶段,那么可能在表单基于的模型中?

谢谢你的帮助!

W.

我的方法是从 here

借来的.但是我使用的是mixin,而不是继承django.forms.Form.这样我可以将它与Form和ModelForm一起使用.此处定义的方法将覆盖BaseForm的_clean_fields方法.

class StripWhitespaceMixin(object):
    def _clean_fields(self):
        for name, field in self.fields.items():
            # value_from_datadict() gets the data from the data dictionaries.
            # Each widget type knows how to retrieve its own data, because some
            # widgets split data over several HTML fields.
            value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))

            try:
                if isinstance(field, FileField):
                    initial = self.initial.get(name, field.initial)
                    value = field.clean(value, initial)
                else:
                    if isinstance(value, basestring):
                        value = field.clean(value.strip())
                    else:
                        value = field.clean(value)
                self.cleaned_data[name] = value
                if hasattr(self, 'clean_%s' % name):
                    value = getattr(self, 'clean_%s' % name)()
                    self.cleaned_data[name] = value
            except ValidationError as e:
                self._errors[name] = self.error_class(e.messages)
                if name in self.cleaned_data:
                    del self.cleaned_data[name]

要使用,只需将mixin添加到表单中即可

class MyForm(StripeWhitespaceMixin, ModelForm):
    ...

此外,如果要在保存没有表单的模型时要修剪空白,可以使用以下mixin.默认情况下,不验证没有表单的模型.当我根据从外部rest api调用返回的json数据创建对象时,我使用它.

class ValidateModelMixin(object):
    def clean(self):
        for field in self._meta.fields:
            value = getattr(self, field.name)

            if value:
                # ducktyping attempt to strip whitespace
                try:
                    setattr(self, field.name, value.strip())
                except Exception:
                    pass

    def save(self, *args, **kwargs):
        self.full_clean()
        super(ValidateModelMixin, self).save(*args, **kwargs)

然后在你的models.py中

class MyModel(ValidateModelMixin, Model):
    ....

翻译自:https://stackoverflow.com/questions/8320739/django-where-to-clean-extra-whitespace-from-form-field-inputs


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Database Design and Implementation

Database Design and Implementation

Edward Sciore / Wiley / 2008-10-24 / 1261.00 元

* Covering the traditional database system concepts from a systems perspective, this book addresses the functionality that database systems provide as well as what algorithms and design decisions will......一起来看看 《Database Design and Implementation》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码