我试图在旁白栏中显示与某篇文章相似的帖子。像 youtube 这样的功能网站甚至堆栈溢出。由于没有人询问,我假设列在旁边的文章具有相似的标签。但它没有工作,它说什么都不匹配。这是我的 post_detail.html 中的内容:
{% block content %}
<div class="row" style="margin-top: 70px">
<div class="col-sm-8">
{% if instance.image %}
<img src='{{ instance.image.url }}' class="img-responsive" />
{% endif %}
<p>Share on:
<a href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}">
Facebook
</a>
<a href="https://twitter.com/home?status={{ instance.content | truncatechars:80 | urlify }}%20{{ request.build_absolute_uri }}">
Twitter
</a>
<a href='https://plus.google.com/share?url={{ request.build_absolute_uri }}'></a>
<a href="https://www.linkedin.com/shareArticle?mini=true&url={{ request.build_absolute_uri }}&title={{
instance.title }}&summary={{ share_string }}&source={{ request.build_absolute_uri }}">
Linkedin
</a>
</p>
<h1>{{ title }}<small>{% if instance.draft %}<span style="color:red"> Draft</span>{% endif %} {{instance.publish}}</small></h1>
{% if instance.user.get_full_name %}
<p>By {{ instance.user.get_full_name }}</p>
{% else %}
<p>Author {{ instance.user }}</p>
{% endif %}
<p><a href='{% url "posts:list" %}'>Back</a></p>
<p><a href='{% url "posts:delete" instance.id %}'>delete</a></p>
<p>{{instance.content | linebreaks }}</p>
<hr>
</div>
<div class="panel panel-default pull-right" style="height: 1000px">
<div class="panel-heading">
<h3 class="panel-title">Similar Articles</h3>
</div>
==========right here====================
<div class="panel-body">
{% for tag in instance.tags.all %}
<h4> <a href="{% url 'posts:detail' slug=tag.slug %}"> {{ tag.title }}</a> </h4><hr>
{% endfor %}
</div>
==========right here====================
</div>
</div>
{% endblock content %}
这是我的看法
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if instance.publish > timezone.now().date() or instance.draft:
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
share_string = quote_plus(instance.content)
context = {
"title": "detail",
"instance": instance,
"share_string": share_string,
}
return render(request, "posts/post_detail.html", context)
如果这种方法超出语法修正范围,需要重写。我不介意以正确的方式写它。这是我使用 Django 的第二个月。对我来说,这种方式是有道理的,但它不起作用。像 youtube 这样的网站是否在主视频的右侧有一个视频和类似的视频,这些视频在那里是因为它们共享相似的标签吗?欢迎任何帮助。
请您参考如下方法:
从长远来看,不要使用已经尝试和测试过的可重用 Django 应用程序重新发明轮子是明智的方法。在你的情况下有这样的应用程序:django-taggit 并且易于使用:
你安装它
pip install django-taggit将其添加到您已安装的应用中:
INSTALLED_APPS = [ ... 'taggit', ]将其自定义管理器添加到您想要标记的模型
from django.db import models from taggit.managers import TaggableManager class YourModel(models.Model): # ... fields here tags = TaggableManager()您可以在您的 View 中使用它:
all_tabs = instance.tags.all()
它甚至有一个 similar_objects()方法:
Returns a list (not a lazy QuerySet) of other objects tagged similarly to this one, ordered with most similar first.
编辑
要检索类似的帖子,您应该使用:
similar_posts = instance.tags.similar_objects()
并且只获得第一个,比方说,5 个类似的帖子:
similar_posts = instance.tags.similar_objects()[:5]
其中 instance 是 Post 模型的实例。
