0

我有一个将新闻项目发布到数据库的 ModelForm,它使用 javascript textarea 来允许授权的发布者插入某些 HTML 来设置文本样式,例如粗体和斜体。但是,由于我使用“安全”过滤器进行模板输出,因此它会输出表单小部件尝试传递的所有 HTML。这包括一个永远不会消失的麻烦<br>标签,使您可以在没有表单验证的情况下提交,将字段读取为空并阻止您。我怎样才能使我不仅可以过滤<br>标签,而且可以将其从数据中完全删除?以下是相关代码:

模型.py:

from django.db import models
from django.forms import ModelForm, forms
from django.contrib.auth.models import User
# Create your models here.

class NewsItem(models.Model):
    user = models.ForeignKey(User)
    date = models.DateField(auto_now=True)
    news = models.TextField(max_length=100000, blank=False, help_text='HELP TEXT')

    def __unicode__(self):
        return u'%s %s %s' % (self.user, self.date, self.news)

class NewsForm(ModelForm):
    class Meta:
        model = NewsItem
        exclude=('user','date',)

视图.py:

from news.models import NewsForm, NewsItem
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse

def news(request):
    if request.method == 'POST':
        item = NewsItem(user=request.user)
        form = NewsForm(request.POST, instance=item)
        if form.is_valid():
            form.save()
        return HttpResponseRedirect('/news/')
    else:
        form = NewsForm()
        news_list = NewsItem.objects.all()
        return render(request, 'news_list.html', {'news_list': news_list, 'form': form})

新闻列表.html:

{% extends "base.html" %}
{% block title %}News in the Corps{% endblock %}

{% block content %}
    <h2 id="page_h">News in the Corps</h2>
    {% if user.is_authenticated %}
    <h3>Post News</h3>
        <script src="{{ STATIC_URL }}nicEdit.js" type="text/javascript"></script>
        <script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script>

        <div id="news_poster">
            <form id="news_poster" action="/news/" method="POST">{% csrf_token %}
            {{ form }} 
            <input type="submit" value="Submit" />
            </form>
        </div>
    {% endif %}
<ul id="events_list">
{% if news_list %}
<div id="news_list">
{% for news in news_list %}
    {% if news.id == 1 %}
    <hr />
    {% endif %}
    <div id="{{ news.id }}" class="news_item">
        <p class="poster">Posted By: {{ news.user }} | Posted On: {{  news.date }} | <a href="{% url 'news' %}#{{ news.id }}">Link</a></p>
        <div id="news_item">
        {{ news.news|safe }}
        </div> 
    </div>
    <hr />
{% endfor %}
</div>
{% endif %}
</ul>
{% endblock %}
4

2 回答 2

1

您可以尝试removetags模板过滤器:

{{ news.news|removetags:"br"|safe }}
于 2013-04-17T06:21:33.873 回答
0

我不禁想到,Timmy O'Mahony 建议的“removetags”如果结构如下,可能会起作用:

{{ news.news|safe|removetags:"br"}}

试一试,看看它是否有效。我会回复,但我的业力不够高,无法直接回复带有建议的答案。

于 2013-04-17T09:08:13.903 回答