Django,模板中怎么做?

时间:2017-04-28 22:47:41

标签: django django-templates django-views

我需要这样显示:

objects.get()

但是当我使用时(如果我评价第一场比赛) {% for x in user_rate %} Your rate : {{x.rate}} {% endfor %} 它在游戏中显示“编辑”而没有费率。 class Rate(models.Model): game = models.ForeignKey(Games) user = models.ForeignKey(User) rate = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)]) class Meta: unique_together = ['game', 'user'] 给我: “get()返回多个Rate - 它返回2!”

我要显示

def game(request, game_id, slug):
    game = Games.objects.get(id = game_id)
    genre = game.genres.all()
    platform = game.platforms.all()
    quantity = Games.objects.all().count()
    user = User.objects.all().count()
    number_of_rates = Rate.objects.filter(game_id = game_id).count()
    rate_average = Rate.objects.filter(game_id = game_id).aggregate(Avg("rate")).values()[0]



    if request.user.is_authenticated():
        user_rate = Rate.objects.filter(user=request.user)


        ctx = {'game' : game, 'genre' : genre, 'platform' : platform, 'quantity' :quantity, \
        'user' : user, 'rate_average' : rate_average, 'user_rate': user_rate, \
       'number_of_rates' : number_of_rates}
        return render(request, 'game.html', ctx)

    else:
        ctx = {'game' : game, 'genre' : genre, 'platform' : platform, 'quantity' :quantity, \
        'user' : user, 'rate_average' : rate_average, 'number_of_rates' : number_of_rates}
        return render(request, 'game.html', ctx)

但这也会显示所有游戏的用户费率。我在评论中有相同的结构,它的作品,我只看到我对这个游戏的评论,但我不知道为什么它不适用于游戏的速度......

$.post( "index.php",{ test: "John"}, function( data ) {
  alert(data);
});

views.py

 $.post( "index.php",{ test: "John"})
  .done(function( data ) {
    alert( "Data Loaded: " + data );
  });

2 个答案:

答案 0 :(得分:0)

# Something along the lines of this.
rate = Rate.objects.get(user=request.user)
context = {...., "user": request.user, "rate": rate}
return render(request, 'template.html', context=context)

在你的模板中:

 {% if rate %}
    <h2><a href="/games/{{game.id}}/{{game.slug}}/add_rate/edit/{{rate.id}}/">Edit rate</a></h2>
{% else %}
     <h2><a href="/games/{{game.id}}/{{game.slug}}/add_rate">Add rate</a></h2>
{% endif %}

答案 1 :(得分:0)

好的,我明白了。我是个傻瓜。 也许有一天会有人使用它。

所以我只需要

Rate.objects.filter(user = request.user, game_id = game_id)

很简单,我遇到了很多问题。