Add a related articles section at the bottom of articles
This commit is contained in:
parent
86b7c280de
commit
843e3bfb0a
2 changed files with 33 additions and 0 deletions
|
@ -1,3 +1,4 @@
|
||||||
|
import random
|
||||||
import re
|
import re
|
||||||
import uuid
|
import uuid
|
||||||
from functools import cached_property
|
from functools import cached_property
|
||||||
|
@ -132,3 +133,21 @@ class Article(AdminUrlMixin, models.Model):
|
||||||
if content:
|
if content:
|
||||||
return readtime.of_html(content).minutes
|
return readtime.of_html(content).minutes
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def get_related_articles(self):
|
||||||
|
related_articles = set()
|
||||||
|
for keyword in self.get_formatted_keywords:
|
||||||
|
potential_articles = Article.objects.filter(
|
||||||
|
keywords__icontains=keyword,
|
||||||
|
status=Article.PUBLISHED,
|
||||||
|
).exclude(pk=self.pk)
|
||||||
|
for article in potential_articles:
|
||||||
|
if keyword in article.get_formatted_keywords:
|
||||||
|
related_articles.add(article)
|
||||||
|
sample_size = min([len(related_articles), 3])
|
||||||
|
return random.sample(related_articles, sample_size)
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def get_formatted_keywords(self):
|
||||||
|
return list(map(lambda k: k.strip().lower(), self.keywords.split(",")))
|
||||||
|
|
|
@ -17,4 +17,18 @@
|
||||||
{{ article.get_formatted_content|safe }}
|
{{ article.get_formatted_content|safe }}
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
|
{% if article.get_related_articles %}
|
||||||
|
<section>
|
||||||
|
<hr>
|
||||||
|
<h4>You might also like</h4>
|
||||||
|
{% for related in article.get_related_articles %}
|
||||||
|
<article>
|
||||||
|
<h5>
|
||||||
|
<a href="{% url "article-detail" slug=related.slug %}">{{ related.title }}</a>
|
||||||
|
</h5>
|
||||||
|
<p>{{ related.get_description }}</p>
|
||||||
|
</article>
|
||||||
|
{% endfor %}
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
Reference in a new issue