Reputation: 506
In my Django project, If the user makes a mistake when signing up, then an error is sent to my template and then displayed. Some of my error messages I send to the user are a bit lengthy, and therefore I want to start a new line within the text. I attempt to add \n within my text, however a new line isn't started.
Here's my code: views.py:
return render(request, 'users/signup.html', {'error': 'Username field must be \n a minimum of 5 characters'})
signup.html:
{% if error %}
<span class="errorspansignup"> {{ error }} </span>
{% endif %}
The text I pass as error stays all on one line.
Does anybody know what the issue is? Thank you.
Upvotes: 1
Views: 1182
Reputation: 557
Use the linebreaks filter
For example:
{{ error|linebreaks }}
If error is Username field must be \n a minimum of 5 characters
, the output will be <p>Username field must be <br> a minimum of 5 characters</p>.
Upvotes: 4
Reputation: 166
Working solution for the above situation:
Use <br>
tag in the error string like below (views.py):
return render(request, 'users/signup.html', {'error': 'Username field must be <br> a minimum of 5 characters'})
And use richtext
filter in the template (signup.html):
{% load wagtailcore_tags ... %}
...
{% if error %}
<span class="errorspansignup"> {{ error|richtext }} </span>
{% endif %}
Note: To load richtext
filter we need to load wagtailcore_tags
.
Upvotes: 1
Reputation: 197
You can do this in two ways.
1)Assuming that the \n
in the passed dictionary corresponds to a newline and in html \n
doesn't help much so can replace \n
with &13;
or <br>
which will take the rest of the text to a newline.
For this particular case you can try this:
return render(request, 'users/signup.html', {'error': 'Username field must be a minimum of 5 characters'})
or
return render(request, 'users/signup.html', {'error': 'Username field must be <br> a minimum of 5 characters'})
2)or you can try using CSS whitespace
in the template setting it to pre-line or pre-wrap,which would wrap up the text according to the corresponding conditons.
Here you can try this :
{% if error %}
<span style="white-space: pre-line;"class="errorspansignup"> {{ error }} </span>
{% endif %}
Try this and see if any of the above two work.Feel free to ask further doubts.
Upvotes: 1