如何在模板中应用upvote功能和相应的模型?

时间:2018-01-06 19:18:46

标签: python django django-templates django-orm

我正在Django开发一个类似{% extends 'base.html' %} {% block title %} {{ question.title }} {% endblock %} {% block body %} <h3><i>{{ question.title }}</i></h3> {{ question.description }} {% for answer in question.answer_set.all %} <br> <div> <p>{{ answer.answer_text }} <span style="font-size: 15px">by [{{ answer.user }}]</span></p> <form method="post" action="{% url 'answer:detail' question.id %}"> {% csrf_token %} <input type="hidden" name="type" value="vote"> <input type="hidden" name="answer_id" value="{{ answer.id }}"> {% for upvote in answer.upvote_set.all %} {% if upvote.user == request.user %} <input type="submit" class="btn btn-sm btn-warning" value="Downvote|{{ answer.upvote_set.all.count }}"> {% else %} {% if forloop.counter == 1 %} <input type="submit" class="btn btn-success" value="Upvote|{{ answer.upvote_set.all.count }}"> {% endif %} {% endif %} {% empty %} <input type="submit" class="btn btn-sm btn-success" value="Upvote|{{ 0 }}"> {% endfor %} </form> {% endfor %} {% endblock %} 的app,但面临两个问题。我想,在问题详情视图中,如果用户没有提出答案,那么它将显示upvote选项和总投票。

这是我的html模板。

from django.contrib.auth.models import User
from django.db import models
from django.shortcuts import reverse


# Create your models here.

class Question(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=200, blank=True, null=True)
    description = models.TextField()
    pub_date = models.DateTimeField()

    def __str__(self):
        return self.title


class Answer(models.Model):
    answer_text = models.TextField()
    questions = models.ForeignKey(Question)
    pub_date = models.DateTimeField(auto_now_add=True)
    # upvote = models.IntegerField(null=True, blank=True)
    user = models.ForeignKey(User)

    def __str__(self):
        return self.answer_text

    def get_absolute_url(self):
        return reverse('answer:answer_by_me', kwargs={'pk': self.user.id})


class Upvote(models.Model):
    user = models.ForeignKey(User)
    answers = models.ForeignKey(Answer)

    def __str__(self):
        return self.user.username

models.py

answer.upvote_set.all

如果用户和任何其他用户已经投票,则显示upvote和downvote按钮。 如果在if request.user in answer.upvote_set.all中找到用户的投票,我就无法使用break关键字,即使我无法使用{{1}}之类的成员资格运算符,因为它会返回upvote对象查询集。我该怎么解决这个问题?

1 个答案:

答案 0 :(得分:1)

您必须为此创建custom tag

在名为templatetags的应用的upvote_tags.py文件夹中创建一个文件。

from django import template

register = template.Library()

@register.simple_tag
def has_upvoted(user, answer):
    return user.id in list(answer.upvote_set.all().values_list("user", flat=True))

现在,您可以在模板中使用它。

# load tag at top of your html.
{% load upvote_tags %}

...
# remove your loop and use condition as below 
{% if has_upvoted request.user answer %}
   # show downvote button for this answer
{% else %}
   # show upvote button for this answer
{% endif %}

您还必须在settings.py中的libraries关键字下的TEMPLATE列表中输入您的标记文件。

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'libraries':{
               # make your file entry here.
               'upvote_tags': 'app_name.templatetags.upvote_tags',
            }
        },
    },
]