typeidea icon indicating copy to clipboard operation
typeidea copied to clipboard

代码完善:《Django企业开发实战》2020年3月河北第6次印刷第197页

Open MaoningGuan opened this issue 5 years ago • 0 comments

书中最新评论的模板代码如下:

<ul>
    {% for comment in comments %}
    <li><a href="{{ comment.target }}">{{ comment.target.title }}</a> |
    {{ comment.nickname }} : {{ comment.content }}
    </li>
    {% endfor %}
</ul>

因为此时的 comment.target 里面的数据是评论目标页面的绝对路径如:

/post/19.html

所以此时的comment.target.title需要进行修改,应该修改为评论目标文章的标题。


修改参考思路: 在我的项目中,是给comment增加了一个新的字段target_title用于存储评论目标文章的标题。 (1)在comment/models.py中添加字段:

target_title = models.CharField(max_length=255, verbose_name='评论目标的标题')

(2)运行:

python manage.py makemigrations
python manage.py migrate

更新数据库。此时,命令行可能提示Comment模型对应的表已经存在评论记录了,这是你们之前评论时产生的记录存储在数据库中了。这时,你可以把之前的评论记录删掉,再运行以上代码,或者按照命令行提示给之前的评论记录输入默认的值。 (3)更改自定义标签,增加多一个参数target_title: comment/templatetags/comment_block.py

from django import template

from comment.forms import CommentForm
from comment.models import Comment

register = template.Library()


@register.inclusion_tag('comment/block.html')
def comment_block(target, target_title):
    return {
        'target': target,
        'target_title': target_title,
        'comment_form': CommentForm(),
        'comment_list': Comment.get_by_target(target)
    }

(4)修改block.html模板文件: typeidea\themes\bootstrap\templates\comment\block.html:

<hr/>
<div class="comment">
    <form class="form-group" action="/comment/" method="POST">
        {% csrf_token %}
        <input name="target" type="hidden" value="{{ target }}"/>
        <input name="target_title" type="hidden" value="{{ target_title }}"/>
        {{ comment_form }}
        <input type="submit" value="submit">
    </form>
    <!--评论列表-->
    <ul class="list-group">
        {% for comment in comment_list %}
        <li class="list-group-item">
            <div class="nickname">
                <a href="{{ comment.website }}">{{ comment.nickname }}</a>
                <span>{{ comment.created_time}}</span>
            </div>
            <div class="comment-content">
                {{ comment.content }}
            </div>
        </li>
        {% endfor %}
    </ul>
</div>

只是增加一个input标签,用于给target_title字段赋值。

<input name="target_title" type="hidden" value="{{ target_title }}"/>

(5)修改模板标签中对评论的引用: detail.html:

{% comment_block request.path post.title %}

links.html:

{% comment_block request.path "友情链接" %}

(6)修改sidebar_comments.html模板文件:

<ul>
    {% for comment in comments %}
    <li><a href="{{ comment.target }}">{{ comment.target_title |slice:"20"|add:"..." }}</a> |
    {{ comment.nickname }} : {{ comment.content }}
    </li>
    {% endfor %}
</ul>

在这里就可以获取到评论目标的标题comment.target_title了。 在此,只是截取标题的前20个字符,并拼接"..."字符串作为结尾。

MaoningGuan avatar Jun 17 '20 17:06 MaoningGuan