html表中的新行

时间:2016-07-23 14:31:19

标签: html django

我的模特:

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')

我的descrizione字段(例如):

descrizione = 'line1 <br> line2'

编辑:添加了关于此字段的内容,请参阅下面的/编辑

我也试过了:

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

我的模板:

<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>

我期待:

line1

line2

在我的表的同一个字段中,而不是我获得:

line1 <br> line2

我的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)

我使用bootstrap,firefox,windows7

感谢您的帮助

编辑:

也许这会增加descrizione字段的方式,所以:

我的populate脚本:

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()

在我的数据库中,我读了

long line1 <br> long line2

在源页面中(在浏览器上右键单击页面,查看源页面或类似内容,我不会使用英文版本)我读到:     long line1&lt; br&gt;长线2

在我的填充脚本中,我也试过了:

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

1 个答案:

答案 0 :(得分:3)

使用descrizione = models.TextField(max_length=500, blank=True, null=True)代替descrizione = models.CharField(max_length=500, blank=True, null=True)

使用{% autoescape off %}{{ aff.affiliazione.descrizione }}{% endautoescape %}代替{{ aff.affiliazione.descrizione }}

一般来说django会转义所有html标签并渲染为原始文本,为了渲染实际的html,你也可以使用{{ aff.affiliazione.descrizione|safe }}