Django TextField 和 CharField 正在剥离空格和空行 [英] Django TextField and CharField is stripping spaces and blank lines

查看:21
本文介绍了Django TextField 和 CharField 正在剥离空格和空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚研究了我的错误",结果发现这是 Django 1.9 中的一个新功能,即默认情况下 CharFields 会去除空格:https://docs.djangoproject.com/en/1.9/ref/forms/fields/#django.forms.CharField.strip

I just researched my "bug" and it turned out to be a new feature in Django 1.9 that CharFields strip spaces by default : https://docs.djangoproject.com/en/1.9/ref/forms/fields/#django.forms.CharField.strip

将相同的接缝应用于文本字段 TextField.

The same seams to apply to text fields TextField.

所以我发现了为什么 Django 的行为突然与以前不同了,但是有没有一种简单的方法可以恢复自动生成的管理表单之前的默认设置?

So I found out why Django suddenly behaves differently than before, but is there an easy way to restore the previous default for auto generated admin forms?

我不想在仍然使用管理员自动生成的表单时去除空格.这还有可能吗?

I would like to NOT strip spaces while still using the auto generated form from the admin. Is that still possible?

推荐答案

如果您正在寻找一个 text/char 字段并且不希望它去除空格,您可以在表单的构造方法中设置 strip=False 并然后在管理员中使用表单

If you are looking for a text/char field and do not want it to strip white spaces you can set strip=False in the constructor method of a form and then use the form in the admin

class YourForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(YourForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].strip = False

    class Meta:
        model = YourModel
        fields = "__all__"

然后您可以通过在 admin.py 文件中指定 form=YourForm 在管理员中使用此表单.

You can then use this form in the admin by specifying form=YourForm in the admin.py file.

这篇关于Django TextField 和 CharField 正在剥离空格和空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆