2

I have a django application using models.CharField. The issue is trailing whitespace is removed, which weirdly enough, I DO NOT WANT TO HAPPEN.

I am only accessing the field through the Admin, not a form. I understand through other posts that forms have an strip = False option, but models do not.

Is there an easy way I can achieve this?

carl
  • 359
  • 2
  • 10

1 Answers1

6

Thanks Willem, but I wasn't exactly sure how to do that.

That said, I've worked it out myself, with a little help from Django TextField/CharField is stripping spaces/blank lines.

Step by step for those still learning, like me:

  1. Define a custom form, overriding the init method (forms.py)
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__"
  1. Reference the custom form when defining the model admin (admin.py)
from .forms import YourForm

class YourModelAdmin(admin.ModelAdmin):
    # list_display, ordering etc.

    form = YourForm

carl
  • 359
  • 2
  • 10