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

查看:178
本文介绍了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天全站免登陆