我想在用户帖子上创建一个like / follow系统。
由于许多用户能够喜欢帖子而且用户能够喜欢很多帖子,所以我制作了2个单独的模型。
Models.py:
class Question(models.Model):
user= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.TextField()
content = models.TextField()
date_published = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(_('Last Edited'), auto_now=True)
slug = models.SlugField(max_length=255)
class Question_Follows(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
count = models.IntegerField(default=0)
views.py
class QuestionDetailView(DetailView):
model = Question
slug = 'slug'
template_name = "questions/question_detail.html"
def get_context_data(self, **kwargs):
context = super(QuestionDetailView, self).get_context_data(**kwargs)
context['now'] = timezone.now()
#obj= Question_Follows.objects.filter(id=question.id)
#context['follow_count'] = Question_Follows.objects.filter(id='question.id')
#obj.count <----- none of these have worked so far.
return context
detailview.html:
<div id="question_container">
<input type='hidden' id="{{ object.id }}" name="id"> <--- tried this as a way to get question id -->
<h1>{{ object.title }}</h1>
<p>{{ object.content }}</p>
<p>Published: {{ object.date_published|date }}</p>
<p>Date: {{ now |date }}</p>
<button class="follow"><span id='follow-span'>Follow| <strong id='follow-count'>{{ follow_count }}</strong> </button>
</span></button>
我在按下“喜欢”按钮后“收集”正确的问题时遇到问题,并且还显示问题的正确数量,即每个问题的跟随计数。
答案 0 :(得分:0)
几点:
count = models.IntegerField(default=0)
模型上的Question_Follows
。每次用户关注问题时,都会在数据库表中为此模型创建一个新行。用户可以多次关注同一个问题吗?如果没有,那么你不需要计数字段。在视图中应使用以下内容提供问题的跟随次数:
def get_context_data(self,kwargs):
context = super(QuestionDetailView, self).get_context_data(**kwargs)
context['now'] = timezone.now()
context['follow_count'] = self.object.follows.count()
return context
请注意,您需要为外键添加相关名称,因此question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='follows')
可以使用该名称。
Question_Follows
将是QuestionFollow
。有关模板问题的进一步问题,请参阅我的评论 - 我怀疑您使用的是错误的模板文件名。