fabio fabio - 4 months ago 12
HTML Question

New line in html table

My model:

class Affiliation(models.Model):
name = models.CharField(max_length=32)
slug = models.SlugField(unique=True)
descrizione = models.CharField(max_length=500, blank=True, null=True)

class Reg_Affiliation(models.Model):
reg = ...
affiliazione = models.ForeignKey(Affiliation, null=True,
on_delete=models.CASCADE, related_name='affiliation_conoscenza')


My
descrizione
field (for example):

descrizione = 'line1 <br> line2'


edit: added something about this field, see below /edit

I tried too:

descrizione = "line1 '<br>' line2"
descrizione = 'line1 "<br>" line2'
descrizione = 'line1 \n line2'
descrizione = 'line1 \r\n line2'


My template:

<div class="panel panel-default">
<table class="table table-striped table table-bordered table table-hover table table-condensed">
<thead>
<tr>
<th>Nome</th>
<th>Descrizione</th>
</tr>
</thead>

<tbody>
{% for aff in lista %}
<tr>
<td>
<b>{{ aff.affiliazione }}</b>
</td>
<td>
{{ aff.affiliazione.descrizione }}
</td>
</tr>
{% endfor %}
</tbody>
</table>




I expect:

line1

line2


in the same field of my table, instead I obtain:

line1 <br> line2


My
views
:

@login_required
def affiliation_list(request):
lista_a=[]
for a in Affiliation.objects.all():
ra=Reg_Affiliation(affiliazione=a,
conoscenza=c,
rapporto=r)
lista_a.append(ra)
context_dict['lista'] = lista_a
return render(request, 'core/affiliation_list.html', context_dict)


I'm using bootstrap, firefox, windows7

Thank you for your help

edit:

maybe it make difference how I add the
descrizione
field, so:

My
populate
script:

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sitoposs.settings')

import django
django.setup()

def populate():

affiliation1 = add_affiliation('name affiliation1', '''long line1 <br> long line2''')
affiliation2 =
...

def add_affiliation(name, descrizione):
a = Affiliation.objects.get_or_create(name=name)[0]
a.descrizione=descrizione
a.save()
return a

if __name__ == '__main__':
populate()


In my database I read

long line1 <br> long line2


In source page (on the browser right click on the page, view source page or something like that, I don't use english version) I read:
long line1 <br> long line2

In my populate script I tried also:

affiliation1 = add_affiliation('name affiliation1', 'long line1 and <br> long line2 in the same line, so unreadable')

Answer

use descrizione = models.TextField(max_length=500, blank=True, null=True) instead of descrizione = models.CharField(max_length=500, blank=True, null=True)

and

use {% autoescape off %}{{ aff.affiliazione.descrizione }}{% endautoescape %} instead of {{ aff.affiliazione.descrizione }}

Generally django escape all html tag and render as raw text, to render actual html you can also use {{ aff.affiliazione.descrizione|safe }}

Comments