如何重定向到django中的上一页?

时间:2012-07-17 15:32:15

标签: django page-refresh django-1.2

我是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 %}

我正在这样做的方式现在它将我重定向到books / vote / x 我希望它重定向到上一页,即books /

请知道 提前致谢

1 个答案:

答案 0 :(得分: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}