Reputation: 5390
I'm new to 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):
@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:
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/
Any idea please Thanks in advance
Upvotes: 1
Views: 1868
Reputation: 5390
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
@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}
Upvotes: 1