如何从视图中增加django整数字段?

时间:2015-10-02 14:16:13

标签: django python-2.7 django-forms django-views django-database

我正在创建一个Django 1.8.4 Web应用程序来提交具有向上投票和向下投票功能的链接。但每次我点击向上投票按钮,它都适用于提交的最后一个链接。我正在使用表单来完成它。表格很正常:

class VoteForm(forms.ModelForm):
    class Meta:
        model = Vote
        exclude = ("vote_type", "vote_date",)

这是模特:

class Link(models.Model):
    title       = models.CharField(max_length=200)
    ...
    up_votes    = models.IntegerField(default=0, blank=True, db_index=True)
    down_votes  = models.IntegerField(default=0, blank=True, db_index=True)
    ...

class Vote(models.Model):
    UP, DOWN = range(2)
    TYPE_CHOICES = [(UP, "Upvote"), (DOWN, "DownVote")]

    voter = models.ForeignKey(User)
    link = models.ForeignKey(Link, related_name='votes')
    vote_type = models.IntegerField(choices=TYPE_CHOICES, db_index=True, null=True)
    vote_date = models.DateTimeField(db_index=True, auto_now=True)

并且视图处理投票:(我猜它仍然是如此简单和愚蠢)

class VoteFormView(FormView):
    form_class = VoteForm

    def form_valid(self, form):
        link = get_object_or_404(Link, pk=form.data["link"])
        user = self.request.user
        prev_votes = Vote.objects.filter(voter=user, link=link)
        has_voted = (prev_votes.count()>0)

        if not has_voted:
            Vote.objects.get_or_create(voter=user, link=link)
            Link.objects.filter(pk=form.data["link"]).update(up_votes=F('up_votes')+1)
            print("+voted")
        else:
            pass
        return redirect("home")

这里的想法是检查当前用户是否已投票给该链接,如果她没有,则增加相应链接对象的up_votes字段。但现在它只增加最后一个link.object.up_votes。

1 个答案:

答案 0 :(得分:0)

正如您在评论中看到的那样,由错误的pk发送到视图引起的问题,我错误地在模板中关闭标记。只是为了记录,我在这里粘贴了模板代码的一部分:

{% for link in object_list %}
<form method="POST" action="{% url 'vote' %}" class="vote_form">
    <li> 
        {% csrf_token %}
        <input type="hidden" id="id_link" name="link" class="hidden_id" value="{{ link.pk }}"/>
        <input type="hidden" id="id_link" name="voter" class="hidden_id" value="{{ user.pk }}"/>
        <button>+</button>
        [{{ link.up_votes }}] 
        <a href="{{ link.url }}">
            <h3>{{ link.title }}</h3>
        </a> 
        <a href="{% url 'link_detail' pk=link.id slug=link.title|slugify %}">
            Comments
        </a>
        <p>
            Submitted by: <a href="{% url 'profile' slug=link.submitter%}"> {{ link.submitter }}</a>
        </p>
    </li>
    </form>
{% endfor %}