[Django]-Is there a way to prevent Django from trimming leading white space in a text field?

6👍

Yes, you form field should set strip=False [Django-doc] in the form, so:

class MyForm(forms.Form):
    some_field = forms.CharField(strip=False)

For a serializer this is quite similar, in your serializer you should set trim_whitespace=False [DRF-doc]:

from rest_framework import serializers

class SongSerializer(ModelSerializer):
    lyrics = serializers.CharField(trim_whitespace=False)

As the documentation says:

If True (default), the value will be stripped of leading and trailing whitespace.

If you render the data then multiple (leading) spaces will be rendered on the webpage as one space. You can make use of <pre> tag as a preformatted text element, so:

{{ some_variable }}

Leave a comment