Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newline in label for Django form field

Is there a way to put a newline in the label of a form field in Django? Putting a \n just results in a newline in the HTML, and trying <br> just displays the characters as they are. Is there an equivalent |safe operation that I can specify on the field?

like image 386
Andrew C Avatar asked Jul 25 '12 15:07

Andrew C


2 Answers

You can also do this directly in the template as follows:

 {{my_field.label|linebreaks}} 

\n will convert to <br/> that way

As per the doc,

a single newline becomes an HTML line break (<br />) and a new line followed by a blank line becomes a paragraph break (</p>).

like image 118
Anupam Avatar answered Nov 14 '22 09:11

Anupam


You can use mark_safe so that the <br /> tag is not escaped.

It's equivalent to using safe in the template, so be careful if you're handling user input. If it's a hardcoded string, then it's safe to use.

from django import forms
from django.utils.safestring import mark_safe

class MyForm(forms.Form):
    my_field = forms.CharField(label=mark_safe('my label<br />next line'))
like image 24
Alasdair Avatar answered Nov 14 '22 11:11

Alasdair