I'm new to django, so please be patient :)
Like many before, I'm trying to build a reddit clone. I've got it all working, but one part is missing. Without producing too many database requests, I would like to indicate whether the current user has voted for a specific question.
This is what my models look like:
from django.db import models
from django.conf import settings
from mptt.models import MPTTModel, TreeForeignKey
max_post_length = 2000
class Thread(models.Model):
title = models.CharField(max_length=200)
text = models.TextField(max_length=max_post_length)
created = models.DateField()
user = models.ForeignKey(settings.AUTH_USER_MODEL)
userUpVotes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='threadUpVotes')
userDownVotes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='threadDownVotes')
def __str__(self):
return self.title
class Comment(MPTTModel):
title = models.CharField(max_length=200)
text = models.TextField(max_length=max_post_length)
created = models.DateField()
user = models.ForeignKey(settings.AUTH_USER_MODEL)
thread = models.ForeignKey(Thread)
parent = TreeForeignKey('self', related_name='children', blank=True, null=True)
vote_count = models.IntegerField(default=0)
userUpVotes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='commentUpVotes')
userDownVotes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='commentDownVotes')
class MPTTMeta:
order_insertion_by = ['created']
def save(self, *args, **kwargs):
self.vote_count = self.userUpVotes.count() - self.userDownVotes.count()
super(Comment, self).save(*args, **kwargs)
def __str__(self):
return self.title
This is my view:
from django.shortcuts import get_object_or_404, render
from community.models import Thread, Comment
from django.http import HttpResponse
def detail(request, thread_id):
thread = get_object_or_404(Thread, pk=thread_id)
comments = thread.comment_set.all()
return render(request, 'threads/detail.html', {
'thread': thread,
'comments': comments
})
And this is my template:
{% extends "base.html" %}
{% load mptt_tags %}
{% block content %}
<h1>{{ thread.title }}</h1>
<p>{{ thread.text }}</p>
<ul class="comments">
{% recursetree comments %}
<li>
<div class="comment-block clearfix">
<vote-up-down up="{{ node.up_vote_by_user }}"
down="{{ node.user_down_vote }}"
url="/community/comment/{{ node.id }}/vote/"
count="{{ node.vote_count }}"></vote-up-down>
<div class="comment">
<h4>{{ node.title }}</h4>
<div class="text">{{ node.text }}</div>
</div>
</div>
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
{% endblock content %}
What would be the best way to populate node.up_vote_by_user and node.down_vote_by_user? I tried using a user middleware and model methods. I also tried pre-iterating the comments, but that doesn't work together with the recursion used for the list.