3

I have a field on an object, and I render it with a textarea in the Django (3.2) admin UI using this code, something like:

class MyObject(models.Model):
    some_text = prompt = db.CharField(max_length=10000)

# ..

class MyObjectAdmin(admin.ModelAdmin):
    list_display = ('id', 'some_text')

    def formfield_for_dbfield(self, db_field, **kwargs):
        """Use Textarea for some_text.

        See also https://stackoverflow.com/a/431412."""
        formfield = super().formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'some_text':
            formfield.widget = forms.Textarea(attrs={'rows': 10, 'cols': 80})
        return formfield

When I edit in the Django admin UI, if I add empty lines (hitting enter several times), when I save, they all are gone. So, while editing, empty lines:

while editing

But after it's saved, no newlines:

after editing

How do I get the Django admin UI to keep the empty lines (as newlines)?

If I have non-empty lines, it keeps all the newlines.

While editing:

enter image description here

After editing (dumped out to a file), with newlines:

enter image description here

dfrankow
  • 20,191
  • 41
  • 152
  • 214

1 Answers1

4

You need to set strip=False [Django-doc] to disable stripping leading and trailing space:

def formfield_for_dbfield(self, db_field, **kwargs):
    formfield = super().formfield_for_dbfield(db_field, **kwargs)
    if db_field.name == 'some_text':
        formfield.strip = False
        formfield.widget = forms.Textarea(attrs={'rows': 10, 'cols': 80})
    return formfield
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555