2

I have a charfield in a django model:

sheet = models.CharField(max_length=256, blank=True, null=True)

I am using the default sqlite database.

When I add a new object that has trailing whitespace at the end of this field, Django automatically trims the string. Is there a way to avoid this behaviour?

pwwolff
  • 606
  • 1
  • 5
  • 20
  • 3
    The `model.CharField` doesn't remove whitespace. However, `form.CharField` does that by default which can be turned off by passing [`strip=False`](https://docs.djangoproject.com/en/2.1/ref/forms/fields/#django.forms.CharField.strip) argument. But it only works with `forms.CharField`. If you're adding the objects via admin, then that might be the reason for auto trimming. I think overriding the admin form remains your only option. – xyres Jul 24 '19 at 08:08
  • This was it - I was making the changes in the admin interface which I assume also uses the forms.CharField. Went into the shell and updated it like that. – pwwolff Jul 24 '19 at 08:22
  • Does this answer your question? [Django TextField and CharField is stripping spaces and blank lines](https://stackoverflow.com/questions/38995764/django-textfield-and-charfield-is-stripping-spaces-and-blank-lines) – Hunger Jul 29 '21 at 02:37

1 Answers1

2

It turns out that the model doesn't trim whitespace but the forms.CharField does. This is used in the admin interface, which I was using to try to perform the update.

I went into the shell (python manage.py shell) and updated the object directly, which worked.

pwwolff
  • 606
  • 1
  • 5
  • 20