简体   繁体   English

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

[英]how to redirect back to previous page in django?

I'm new to django 我是django的新手

I'm working on a voting application, and I need to stay on the same page after casting a vote 我正在处理投票应用程序,因此我需要在投票后停留在同一页面上

Meaning that I want to refresh the page without leaving it and display a success message 这意味着我想刷新页面而不离开页面并显示成功消息

Here is my view.py (where I set and check cookies to avoid double votes): 这是我的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()

Here is my urls.py: 这是我的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"),  
)

Here is my template : 这是我的模板:

{% if list_participant %}

{% for book in list_books %}

{{ book.name }} 

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

    {{ book.votes }} 

  {% endfor %}

{% endif %}

The way I'm doing it now it redirect me to books/vote/x I'd like it to redirect to the previous page ,which is books/ 我现在的操作方式是将我重定向到books / vote / x,我希望它重定向到上一页,即books /

Any idea please Thanks in advance 任何想法请先谢谢

Solved 解决了

so what I did is to add the vote processing inside the same view that display the books and use an if Post condition to detect when the vote button is clicked 所以我要做的是在显示书籍的同一视图内添加投票处理,并使用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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM