Django TextField and CharField is stripping spaces and blank lines

Andy picture Andy · Aug 17, 2016 · Viewed 7k times · Source

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 TextField.

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?

Answer

Shahrukh Mohammad picture Shahrukh Mohammad · Jun 19, 2018

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.