gpt4 book ai didi

python - 检查当前用户是否投票

转载 作者:太空宇宙 更新时间:2023-11-04 06:23:39 25 4
gpt4 key购买 nike

在我的索引页面上,我需要知道当前用户是否对一本书进行了投票,所以我可以在 <li> 上设置一个类当前用户已经投票的元素。

模板(片段)

{% if top_books %}
<ul>
{% for book in top_books %}
<li id="{{ book.id }}" class="book">
<img class="upvote {% ifequal thisUserUpVote 1 %}selected{% endifequal %}" title="Upvote book (click to undo)" src="{{ STATIC_URL }}images/upvote.png" />
{{ book.score|floatformat }}
<img class="downvote {% ifequal thisUserDownVote 1 %}selected{% endifequal %}" title="Downvote book (click to undo)" src="{{ STATIC_URL }}images/downvote.png" />
<a href="/p/{{ book.id }}/">{{ book.title }}</a>
</li>
{% endfor %}
</ul>

Views.py(片段)

from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from books.models import Book

def index(request):
latest_book = Book.objects.all().order_by('-pub_date')[:5]
top_items = Book.objects.all().order_by('-score')[:100]
return render_to_response('books/index.html', {
'latest_books': latest_books,
'top_books' : top_books},
context_instance=RequestContext(request))

Models.py(片段)

class Book(models.Model):
title = models.CharField(max_length=500)
pub_date = models.DateField()
author = models.ManyToManyField(Author)
userUpVotes = models.ManyToManyField(User, blank=True)
userDownVotes = models.ManyToManyField(User, blank=True)

最佳答案

首先,您的代码将无法正确呈现,因为您将变量传递给 View 中不存在的模板 - 我希望这只是一个拼写错误。

def index(request):
latest_book = Book.objects.all().order_by('-pub_date')[:5]
top_items = Book.objects.all().order_by('-score')[:100]
return render_to_response('books/index.html', {
'latest_books': latest_books, # latest_book
'top_books' : top_books}, # top_items
context_instance=RequestContext(request))

对于您的问题 - 您需要在模板的循环中检查模型的用户是 userUpVotes 还是 userDownVotes:

{% for book in top_books %}
{% if user in book.userupvotes.all %}
{{ user }} has upvoted
{% endif %}
{% if user in book.userdownvotes.all %}
{{ user }} has downvoted
{% endif %}
{% endfor %}

关于python - 检查当前用户是否投票,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10060836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com