ploghubapp/models.py
class VotePost(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    value = models.IntegerField(default=0)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    history = HistoricalRecords()

    def change_vote(self, new_vote_value, request_user):
        if self.value == -1 and new_vote_value == 1:  # down to up
            vote_diff = 2
            self.post.net_votes += 2
            self.post.upvotes += 1
            self.post.downvotes -= 1
        elif self.value == 1 and new_vote_value == -1:  # up to down
            vote_diff = -2
            self.post.net_votes -= 2
            self.post.upvotes -= 1
            self.post.downvotes += 1
        elif self.value == 0 and new_vote_value == 1:
            vote_diff = 1
            self.post.upvotes += 1
            self.post.net_votes += 1
        elif self.value == 0 and new_vote_value == -1:
            vote_diff = -1
            self.post.downvotes += 1
            self.post.net_votes -= 1
        else:
            return None

        if self.post.user != request_user:
            self.post.user.userprofile.submission_karma +=  vote_diff
            self.post.user.userprofile.save()

        self.value = new_vote_value
        self.save()
        self.post.save()
        self.post.user.save()

        return vote_diff

    def unvote(self, request_user):
        if self.value == 1:
            vote_diff = -1
            self.post.upvotes -= 1
            self.post.net_votes -= 1
        elif self.value == -1:
            vote_diff = 1
            self.post.downvotes -= 1
            self.post.net_votes += 1
        else:
            return None
        if self.post.user != request_user:
            self.post.user.userprofile.submission_karma += vote_diff
            self.post.user.userprofile.save()

        self.value = 0
        self.save()
        self.post.save()
        self.post.user.save()
        return vote_diff
ploghubapp/forms.py
class PostEditForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'body']
        widgets = {
            'body': forms.Textarea(attrs={'rows': 15}),
        }
ploghubapp/models.py
class Comment(MPTTModel):
    """
    Represents a comment
    """
    #Fields
    comment_text = models.TextField()
    comment_text_html = models.TextField()
    deleted = models.BooleanField(default=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
    upvotes = models.IntegerField(default=0)
    downvotes = models.IntegerField(default=0)
    net_votes = models.IntegerField(default=0)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class MPTTMeta:
        order_insertion_by = ['-net_votes']
    
    def __str__(self):
        return self.comment_text

    def time_since_posted(self):
        now = timezone.now()
        timediff = now - self.created
        minutes = int(timediff.total_seconds()/60)
        hours = int(minutes/60)
        days = int(hours/24)
        if minutes < 60:
            if minutes == 1:
                return "{} minute ago".format(minutes)
            else:    
                return "{} minutes ago".format(minutes)
        if hours < 24:
            if hours == 1:
                return "{} hour ago".format(hours)
            else:
                return "{} hours ago".format(hours)
        if days == 1:
            return "{} day ago".format(days)
        else:
            return "{} days ago".format(days)
    
    def can_delete(self):
        if self.deleted:
            return False
        now = timezone.now()
        timediff = now - self.created
        minutes = int(timediff.total_seconds()/60)
        hours = int(minutes/60)
        if hours <= 1 and Comment.objects.filter(parent=self).filter(deleted=False).count() == 0:
            return True
        else:
            return False
    
    def can_edit(self):
        if self.deleted:
            return False
        now = timezone.now()
        timediff = now - self.created
        minutes = int(timediff.total_seconds()/60)
        hours = int(minutes/60)
        if hours <= 1:
            return True
        else:
            return False
    
    def get_post_url(self):
        slug = slugify(self.post.title)
        return reverse('ploghubapp:view_post', args=[self.post.id, self.post.user, slug])
ploghubapp/models.py
class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    about = models.CharField(max_length=1000, default="[empty]")
    comment_karma = models.IntegerField(default=0)
    submission_karma = models.IntegerField(default=0)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    history = HistoricalRecords()
ploghubapp/models.py
class VoteComment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
    value = models.IntegerField(default=0)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    history = HistoricalRecords()

    def change_vote(self, new_vote_value, request_user):
        if self.value == -1 and new_vote_value == 1:  # down to up
            vote_diff = 2
            self.comment.net_votes += 2
            self.comment.upvotes += 1
            self.comment.downvotes -= 1
        elif self.value == 1 and new_vote_value == -1:  # up to down
            vote_diff = -2
            self.comment.net_votes -= 2
            self.comment.upvotes -= 1
            self.comment.downvotes += 1
        elif self.value == 0 and new_vote_value == 1:
            vote_diff = 1
            self.comment.upvotes += 1
            self.comment.net_votes += 1
        elif self.value == 0 and new_vote_value == -1:
            vote_diff = -1
            self.comment.downvotes += 1
            self.comment.net_votes -= 1
        else:
            return None

        if self.comment.user != request_user:
            self.comment.user.userprofile.comment_karma +=  vote_diff
            self.comment.user.userprofile.save()

        self.value = new_vote_value
        self.save()
        self.comment.save()
        self.comment.user.save()

        return vote_diff

    def unvote(self, request_user):
        if self.value == 1:
            vote_diff = -1
            self.comment.upvotes -= 1
            self.comment.net_votes -= 1
        elif self.value == -1:
            vote_diff = 1
            self.comment.downvotes -= 1
            self.comment.net_votes += 1
        else:
            return None
        if self.comment.user != request_user:
            self.comment.user.userprofile.comment_karma += vote_diff
            self.comment.user.userprofile.save()

        self.value = 0
        self.save()
        self.comment.save()
        self.comment.user.save()
        return vote_diff
ploghubapp/forms.py
class CommentEditForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['comment_text']
ploghubapp/models.py
class Post(models.Model):
    """
    Represents a link to an external learning resource
    """

    #Fields
    title = models.CharField(max_length=150)
    body = models.CharField(max_length=20000)
    body_html = models.TextField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    deleted = models.BooleanField(default=False)
    upvotes = models.IntegerField(default=0)
    downvotes = models.IntegerField(default=0)
    net_votes = models.IntegerField(default=0)
    rank = models.FloatField(default=0.0)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    history = HistoricalRecords()

    def __str__(self):

        return self.title

    def calculate_rank(self, comments_count):
        now = timezone.now()
        timediff = now - self.created
        minutes = int(timediff.total_seconds()/60)
        hours = int(minutes/60)

        comment_weight = 0.2
        gravity = 1.5
        amplifier = 100000

        rank = (self.net_votes +(comments_count*comment_weight) - 1)/pow(hours+2,gravity)*amplifier
        self.rank = rank
        self.save()

    def time_since_posted(self):
        now = timezone.now()
        timediff = now - self.created
        minutes = int(timediff.total_seconds()/60)
        hours = int(minutes/60)
        days = int(hours/24)
        if minutes < 60:
            if minutes == 1:
                return "{} minute ago".format(minutes)
            else:    
                return "{} minutes ago".format(minutes)
        if hours < 24:
            if hours == 1:
                return "{} hour ago".format(hours)
            else:
                return "{} hours ago".format(hours)
        if days == 1:
            return "{} day ago".format(days)
        else:
            return "{} days ago".format(days)
    
    def get_post_url(self):
        slug = slugify(self.title)
        return reverse('ploghubapp:view_post', args=[self.id, self.user, slug])
    
    def can_delete(self):
        if self.deleted:
            return False
        now = timezone.now()
        timediff = now - self.created
        minutes = int(timediff.total_seconds()/60)
        hours = int(minutes/60)
        if hours <= 23 and Comment.objects.filter(post=self).filter(deleted=False).count() == 0:
            return True
        else:
            return False
ploghubapp/forms.py
class PostModelForm(ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'body']
        widgets = {
            'body': forms.Textarea(attrs={'rows': 15}),
        }
ploghubapp/forms.py
class RegisterForm(forms.Form):
    username = forms.CharField(label='Username', max_length=100, validators=[RegexValidator(r'^[a-zA-Z0-9-_]+$', "Only letters, digits, hyphen and underscore without spaces are allowed")])
    password = forms.CharField(label='Password', max_length=100, widget=forms.PasswordInput)
    email = forms.EmailField()
ploghubapp/forms.py
class CommentReplyForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['comment_text']
ploghubapp/forms.py
class ProfileForm(forms.Form):
    email = forms.EmailField()
    about = forms.CharField(max_length=1000, widget=forms.Textarea)
ploghubapp/forms.py
class CommentForm(forms.Form):
    comment = forms.CharField(label='Comment', max_length=2000, widget=forms.Textarea)


Question: from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from .forms import RegisterForm, ProfileForm
from django.contrib.auth import views, authenticate, login, get_user_model
from django.contrib import messages
from django.urls import reverse
from django.views.generic import TemplateView, View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
from django.core import exceptions
from django.views import generic
from .forms import PostModelForm, CommentForm, CommentEditForm, CommentReplyForm, PostEditForm
from .models import Post, Comment, VoteComment, UserProfile, VotePost
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from itertools import chain
from operator import attrgetter
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Count
import markdown
import bleach
        form = self.form_class()
        return render(request, self.template_name, {'form' : form})
    
    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            new_username = form.cleaned_data['username']
            new_password = form.cleaned_data['password']
            new_email = form.cleaned_data['email']

            if get_user_model().objects.filter(username=new_username).exists():
                messages.error(request, "Username not available, choose a different one")
                return render(request, self.template_name, {'form' : form})
            if new_email != '' and get_user_model().objects.filter(email=new_email).exists():
                messages.error(request, "Email not available, choose a different one")
                return render(request, self.template_name, {'form' : form})
            
            #validate password
            try:
                validate_password(new_password)
            except exceptions.ValidationError as e:
                form.errors['password'] = list(e.messages)
                return render(request, self.template_name, {'form' : form})

            user = get_user_model().objects.create_user(username=new_username, password=new_password, email=new_email)
            user = authenticate(username=new_username, password=new_password)
            userprofile = UserProfile(user=user)
            userprofile.save()
            if user is not None:
                login(request, user)
                return redirect(reverse('ploghubapp:profile'))
        else:
            return render(request, self.template_name, {'form' : form})

class ProfileView(LoginRequiredMixin, View):
    login_url = '/user/login/'
    form_class = ProfileForm
    template_name = 'registration/profile.html'

    def get(self, request, *args, **kwargs):
        data = {'about' : request.user.userprofile.about}
        if request.user.email != '':
            data['email'] = request.user.email
        form = self.form_class(initial = data)
        return render(request, self.template_name, {'form' : form})
    
    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST, initial={'email' : request.user.email, 'about' : request.user.userprofile.about})
        if form.is_valid():
            if form.has_changed():
                user = request.user
                
                for field in form.changed_data:
                    if field == 'email':
                        if form.cleaned_data[field] != '' and User.objects.filter(email=form.cleaned_data[field]).exclude(id=user.id).exists():
                            messages.error(request, "Email address is already in use")
                            return redirect(reverse('ploghubapp:profile'))
                    setattr(user, field, form.cleaned_data[field])
                user.save()
                user.userprofile.about = form.cleaned_data['about']
                user.userprofile.save()
                messages.success(request, "Profile has been updated")
                return redirect(reverse('ploghubapp:profile'))
            else:
                messages.info(request, "Data has not been changed")
                return redirect(reverse('ploghubapp:profile'))
        else:
            messages.error(request, "Invalid form data")
            return redirect(reverse('ploghubapp:profile'))

class PublicUserProfileView(View):
    template_name = 'registration/public_user_profile.html'

    def get(self, request, username):
        user = get_object_or_404(User, username=username)
        return render(request, self.template_name, {'user' : user})

class WriteView(LoginRequiredMixin, View):
    form_class  = PostModelForm
    template_name = 'ploghubapp/write.html'

    def get(self, request, *args, **kwargs):
        form = self.form_class()
        return render(request, self.template_name, {'form' : form})

    def post(self, request):
        form = self.form_class(request.POST)
        
        if form.is_valid():
            title = form.cleaned_data['title']
            body = form.cleaned_data['body']
            body_html = markdown.markdown(body)
            body_html = bleach.clean(body_html, tags=settings.ARTICLE_TAGS, strip=True)
            article = Post(title=title, body=body, user=request.user, body_html=body_html)

            article.save()
            vote_obj = VotePost(user=request.user,
                                post=article,
                                value=1)
            vote_obj.save()
            article.upvotes += 1
            article.net_votes += 1
            article.save()
            messages.success(request, 'Article has been submitted.')
            return redirect(reverse('ploghubapp:home_page') + '?sort_by=new')
        else:
            return render(request, self.template_name, {'form' : form})

class ViewPost(generic.DetailView):

    template_name = 'ploghubapp/view_post.html'
    form_class = CommentForm

    def get(self, request, pk, username, slug):
        post = get_object_or_404(Post, pk=pk)
        if post.deleted:
            messages.error(request, 'The post you tried to access has been deleted.')
            return redirect(reverse('ploghubapp:home_page'))
        nodes = Comment.objects.filter(post=post).filter(deleted=False)
        if request.user.is_authenticated:

Answer:             user_votes = VoteComment.objects.filter(user=request.user).filter(comment__post=post)