1

我是 Django 新手

我正在处理投票申请,我需要在投票后保持在同一页面上

这意味着我想刷新页面而不离开它并显示成功消息

这是我的 view.py(我在其中设置和检查 cookie 以避免双重投票):

@render_to('user/books_list.html')  
def vote(request, object_id):
voted=request.session.get('has_voted',[])
books = Book.objects.get(id=object_id);

if object_id in voted:         
    return {
                'object': books,
                'error_message': "You have already voted.",
            }
else:
    books.votes += 1
    books.save()
    request.session['has_voted']=voted+[object_id]
    return locals()

这是我的 urls.py:

urlpatterns = patterns('user.views',

    url(r'^books/$', 'books_list', name="books_list"),
    url(r'^books/(?P<object_id>\d+)$', 'book_detail', name="book"),
    url(r'^books/vote/(?P<object_id>\d+)$', 'vote', name="vote"),  
)

这是我的模板:

{% if list_participant %}

{% for book in list_books %}

{{ book.name }} 

    <a href={% url vote book.id %}  >vote</a>

    {{ book.votes }} 

  {% endfor %}

{% endif %}

我现在这样做的方式将我重定向到书籍/投票/x 我希望它重定向到上一页,即书籍/

任何想法请提前谢谢

4

1 回答 1

1

解决了

所以我所做的是在显示书籍的同一视图中添加投票处理,并使用 if Post 条件来检测何时单击投票按钮

@render_to('user/list_books.html')  
def list_books (request):    
    books_list = Book.objects.all()

  if request.POST:
    voted=request.session.get('has_voted',[])
    p_id=request.POST['id']
    book = Book.objects.get(id=p_id);
    if p_id in voted:         
        return {
                'notvoted': book,
                'error_message': "You have already voted for this book today!",
                'books_list': books_list
                }
    else:
        book.votes += 1
        book.save()

        vote = Vote() 
        vote.book_id = p_id
        vote.ip = request.META.get('REMOTE_ADDR')       
        vote.save()

        request.session['has_voted'] = voted+[p_id]
        request.session.set_expiry(86400)#one day in seconds
        return {
                 'books_list': books_list,
                 'voted' : 1 ,
                 'book' : book
                }
else :
    return {'books_list': books_list}
于 2012-07-23T13:34:23.150 回答