功能概要:
【1】收藏模型。
模型会建立和文章的多对一关系,然后记录谁收藏,文章作者,文章标题,收藏时间。
class CltNote(models.Model):
clt_relation_note = models.ForeignKey(MyNote, on_delete=models.CASCADE, related_name=‘clt_note‘)
who_clt = models.CharField(max_length=64)
author = models.CharField(max_length=64)
title = models.CharField(max_length=64)
clt_time = models.DateTimeField(auto_now_add=True)
【2】进行收藏时的模板设计。
首先判断当前用户是不是文章的作者,如果是就可以进行“编辑”,如果不是就可以进行“收藏”相关操作;
然后判断是否已经收藏,如果是,显示提示并且不能进行收藏操作;如果否,提供一个链接,执行views里的某个函数。
{% if request.user.username == pk_note.author %}
<p><a href="{% url ‘notebook:edit_note‘ pk_note.pk %}">编辑</a></p>
{% else %}
{% if if_collect %}
<p>已收藏</p>
{% else %}
<a href="{% url ‘notebook:clt_note‘ pk_note.pk %}">收藏</a>
{% endif %}
{% endif %}
【3】收藏模型的相关处理。
这个函数里,仍然要首先获得用户和文章作者,然后获取收藏模型相关信息,存入数据库;
再将文章的被收藏数+1,然后保存文章。
# 实现收藏功能,保存相关数据
@login_required
def clt_note(request, pk):
current_user = request.user
pk_note = get_object_or_404(MyNote, open_bool=True, id=pk)
new_clt_note = CltNote()
new_clt_note.who_clt = current_user.username
new_clt_note.clt_relation_note = pk_note
new_clt_note.author = pk_note.author
new_clt_note.title = pk_note.title
new_clt_note.save()
pk_note.collect_count += 1
pk_note.save()
return HttpResponseRedirect(reverse(‘notebook:op_one_note‘, args=[pk]))
【4】显示收藏,views部分。
由于收藏的界面会和首页类型,因此需要调用get_ten_comment函数,并获取其返回值;
获取所有的收藏信息中,需要过滤收藏者信息;
在判断是否可以前往到具体文章时,判断这篇文章当前是否仍然设置为开放:open_bool = True;
收藏信息仍然使用分页显示方式。
{% block content %}
<div class="left">
{# show all collect notes with page_id #}
<div>
{% for clt_note in page_obj %}
<p>
<span>收藏时间:{{clt_note.clt_time}}</span>
<span>作者:{{clt_note.author}}</span>
<span>标题:{{clt_note.title}}</span>
{% if clt_note.clt_relation_note.open_bool %}
<a href="{% url ‘notebook:op_one_note‘ clt_note.clt_relation_note.pk %}">前往</a>
{% else %}
<span>作者已设为私有</span>
{% endif %}
</p>
{% endfor %}
</div>
{# function of previous and next #}
<div>
<span>
{% if page_obj.has_previous %}
<a href="{% url ‘notebook:all_clt‘ 1 %}">从头</a>
<a href="{% url ‘notebook:all_clt‘ page_obj.previous_page_number %}">上一页</a>
{% endif %}
<span>
{{page_obj.number}} of {{page_obj.paginator.num_pages}}
</span>
{% if page_obj.has_next %}
<a href="{% url ‘notebook:all_clt‘ page_obj.next_page_number %}">下一页</a>
<a href="{% url ‘notebook:all_clt‘ page_obj.paginator.num_pages %}">到尾</a>
{% endif %}
</span>
</div>
</div>
{% endblock content %}
django要实现收藏功能也很简单。设计一个好的模型至关重要!!!
原文:https://www.cnblogs.com/lzhshn/p/13626118.html