在 Django 中允许每个用户生成 1 个视图

Posted

技术标签:

【中文标题】在 Django 中允许每个用户生成 1 个视图【英文标题】:Allow 1 view generation per user in Django 【发布时间】:2017-09-19 13:22:05 【问题描述】:

有了this question,我想出了下面的代码。

行为应该如下:

    每个Suggestion可以接收多个Vote 每个用户只能使用 1 个Vote

效果很好,但我想知道最好的方法是什么?

vote_form.html

<form action="% url 'add_vote' suggestion.id %" method="post">
    % csrf_token %
    <input type="submit" value="I want to vote">
</form>

urls.py

urlpatterns = [
    url(r'^suggestion/(?P<pk>\d+)/$', views.SuggestionDetail.as_view(), name="suggestion_detail"),
    url(r'^suggestion/(?P<pk>\d+)/vote/$', views.add_vote, name='add_vote'),
] 

models.py

class Vote(models.Model):
    suggestion = models.ForeignKey(Suggestion)
    voter = models.ForeignKey('auth.User')
    vote_count = models.BooleanField()

views.py

def add_vote(request, pk):
    suggestion = get_object_or_404(Suggestion, pk=pk)
    vote = Vote(
        suggestion = suggestion,
        voter = request.user,
        vote_count = True)
    has_user_voted = Vote.objects.filter(voter=request.user, suggestion=suggestion).count()
    if has_user_voted < 1:
        vote.save()
    else:
        messages.error(request, 'It seems you have already voted, only one vote is allowed')
    return HttpResponseRedirect(reverse('suggestion_detail', args=(suggestion.id,)))

【问题讨论】:

vote_count 的数据中是否有 False 值? 它不能,当它被创建时它会得到一个True 【参考方案1】:

第一个解决方案是在模型中添加 unique-together

class Vote(models.Model):
    suggestion = models.ForeignKey(Suggestion)
    voter = models.ForeignKey('auth.User')
    vote_count = models.BooleanField()

    class Meta:
        unique_together = ("suggestion", "voter")

如果vote_count 总是True,你也可以使用get-or-create

def add_vote(request, pk):
    suggestion = get_object_or_404(Suggestion, pk=pk)
    vote, created = Vote.objects.get_or_create(
            voter=request.user,
            suggestion=suggestion,
            vote_count=True)
    if not created:
        messages.error(request, 'It seems you have already voted, only one vote is allowed')
    return HttpResponseRedirect(reverse('suggestion_detail', args=(suggestion.id,)))

【讨论】:

谢谢,我只是不知道如何在模板中呈现错误?我现在得到:/suggestion/7/vote/ 处的 IntegrityError 唯一约束失败:suggest_vote.suggestion_id,suggest_vote.voter_id 请求方法:POST 请求 URL:127.0.0.1:8000/suggestion/7/vote Django 版本:1.11.4 异常类型:IntegrityError 异常值:唯一约束失败: 建议投票.suggestion_id, 建议投票.voter_id

以上是关于在 Django 中允许每个用户生成 1 个视图的主要内容,如果未能解决你的问题,请参考以下文章

在 UIAnimations 中允许 UITapGestureRecognizer

如何在我的 Django Rest Framework 项目中允许所有跨域请求?

我应该在我的用户名中允许表情符号吗?

在 MariaDB 10.3 中允许对特定用户进行外部访问

带有 2 个部分选择的 UITableview

表单字段的 Django 跳过选项