Reputation: 6138
I would like to know if there is a solution in order to make multiple newlines in my Django Charfield Form.
I have a field Description
and I would like to write something inside like :
Hello,
My name is John.
I am 23 years old.
Is it possible to help me ?
Unfortunately, up to now I have :
Hello, My name is John. I am 23 years old. Is it possible to help me ?
My models looks like :
class Ticket(models.Model):
...
Description = models.CharField(max_length=250, verbose_name='Description')
When users are filling Description Field, I would like to set in real-time newlines. As you can see, all strings are in the same line.
How I could do that ?
Upvotes: 2
Views: 6037
Reputation: 11
I had a use case where I wanted allow newline characters to be rendered, as well as to restrict the number of characters in the field to a fixed number (Similar to adding a bio field to a profile). You can combine certain concepts from Templates and Forms to achieve this.
In your model, define the field as a normal CharField
:
description = models.CharField(max_length=250)
In your form, initialize the field as follows:
description = forms.CharField(max_length=250, widget=forms.Textarea(attrs={'rows':4, 'cols':15}))
Using the widget as Textarea
is important here, because if you use the default TextInput
widget, it will submit the form on pressing Enter, rather than inserting a newline. You can change the size of the Textarea to be rendered by using an attrs
dict.
Now, finally to display the content correctly with newlines, inside your template, apply the linebreaks
Django filter:
<p>{{ user.profile.description|linebreaks }}</p>
The linebreaks
filter replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (<br>
) and a new line followed by a blank line becomes a paragraph break (</p>
).
Upvotes: 1
Reputation: 6138
I found a solution. I replaced models.CharField
by models.TextArea
:
Description = models.TextField(max_length=250, verbose_name='Description')
Then in my template, I set :
{{value|linebreaks}}
And it works ! I can make newlines with Caps + Enter
Upvotes: 3