Reputation: 21447
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:
But after it's saved, no newlines:
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:
After editing (dumped out to a file), with newlines:
Upvotes: 3
Views: 374
Reputation: 477160
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
Upvotes: 5