Django TextField/CharField is stripping spaces/blank lines

烂漫一生 提交于 2019-12-18 07:35:29

问题


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

The same seams to apply to text fields. 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?

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


回答1:


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__"

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




回答2:


Try using this:

# fields.py
from django.db.models import TextField


class NonStrippingTextField(TextField):
    """A TextField that does not strip whitespace at the beginning/end of
    it's value.  Might be important for markup/code."""

    def formfield(self, **kwargs):
        kwargs['strip'] = False
        return super(NonStrippingTextField, self).formfield(**kwargs)

And in your model:

class MyModel(models.Model):
    # ...
    my_field = NonStrippingTextField()



回答3:


strip=False 

in the model field for CharFields.


Django TextField do not support this stripping feature so you have to do it on your own. You can use the strip method.

abc.strip()



回答4:


Seems like the best way to handle this is to create a custom admin form like this:

class CustomForm(forms.ModelForm):
    my_field = forms.CharField(strip=False, widget=forms.Textarea)

    class Meta:
        model = MyModel
        exclude = []

This will create a default form with just my_field overwritten with its non stripped version. )this has to be set in the corresponding admin of course. If anybody knows an even simpler version. Please tell me!




回答5:


I was having this issue with django-rest model serializer. The data in my text field was stripped of white space. So if you are trying to do this on the serializer level, you can specify the whitespace param on CharField serializer. Here is the source code signature.

And here is the rest-docs on CharField

class SomeSerializer(serializers.ModelSerializer):
    content = serializers.CharField(trim_whitespace=False)

    class Meta:
        model = YourModel
        fields = ["content"]


来源:https://stackoverflow.com/questions/38995764/django-textfield-charfield-is-stripping-spaces-blank-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!