I want to create a like/follow system on user posts.
Due to many users being able to like a post and users being able to like many posts I made 2 separate models.
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>
I'm having problems 'collecting' the right question once the like button has been pressed and also showing the right number of likes for the question i.e the follow count for each question.
A few points:
count = models.IntegerField(default=0) on the Question_Follows model. A new row is created in the database table for this model every time a user follows a question. Can a user follow the same question more than once? If not, then you don't need a count field.The number of follows for the question should be available in the view using something like:
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
Note that you'll need to add a related name to your foreign key, so it will be question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='follows') for this to work.
Question_Follows would be QuestionFollow.See my comment for further questions related to your template issues - I suspect you are just using the wrong template file name.