无法在Django中应用内联样式

时间:2015-02-19 09:53:37

标签: django django-templates

我想在帖子中设置引号。但无论我做什么,标签都变成了字符,因此变得无效。

观点是:

@login_required
def quote_reply(request, quote_id):
    tform = PostForm()
    print 'user is:' + request.user.username
    quote = Post.objects.get(pk = quote_id)
    topic_id = quote.topic_id
    topic = Topic.objects.get(id= topic_id)


    args = {}
    if request.method == 'POST':
        post = PostForm(request.POST)


        if post.is_valid():

            p = post.save(commit = False)
            p.topic = topic
            p.title = post.cleaned_data['title']
            p.body = '<span style="background-color: yellow; font-size:2em;">' + unicode(quote.body) + '</span>\n\n'+ post.cleaned_data['body'] #problematic line
            p.creator = request.user
            p.user_ip = request.META['REMOTE_ADDR']

            if len(p.title)< 1:

                            p.title= str(request.user.username) + 'wrote:'
            p.save()

            tid = int(topic_id)
            return HttpResponseRedirect('/forum/topic/%s'  % topic_id)

    else:
        args.update(csrf(request))
        args['form'] = tform
        args['post'] = quote
        args['topic_id'] = topic_id
        return render_to_response('myforum/qoute_reply.html', args, 
                                  context_instance=RequestContext(request))

相关模板部分是:

                <ul class="forum-post-body list-unstyled list-inline">
                         <li class="col-md-2 userpanel">{{ post.creator }} <br> </li>

                         {% autoescape on %}
                         <li class="col-md-10">{{ post.body|linebreaks }} </li>
                         {% endautoescape %}
                </ul>

原始html输出结果如下:

<li class="col-md-10"><p>&lt;span style=&quot;background-color: yellow; font-size:2em;&quot;&gt;This is a post</p>

<p>&lt;/span&gt;</p>

我还测试了没有换行过滤器,但它也产生了:

    <li class="col-md-10">&lt;span style=&quot;background-color: yellow; font-size:3em;&quot;&gt;This is a post

&lt;/span&gt;

And here is the reply </li>

欣赏你的提示。

1 个答案:

答案 0 :(得分:1)

您应该关闭autoescape

{% autoescape off %}
<li class="col-md-10">{{ post.body|linebreaks }} </li>
{% endautoescape %}

或使用safe模板过滤器并省略autoescape模板标记:

<li class="col-md-10">{{ post.body|safe|linebreaks }} </li>

要将用户生成的数据安全地嵌入到html代码中,请使用format_html()函数。