I'm trying to extend polls app from tutorial and add a 'user already
voted' check. Can somebody suggest me a way to do that? My current
idea is to add some BLOB filed to polls model and add each voted user
id to list that will be pickled into that field. For anonymous users a
cookie
with poll id should be added.
Not sure if the pickle/unpickle way is the best in terms of used
system resources and speed. Any other suggestions?
--
Sincerely,
Vladimir "Farcaller" Pouzanov
http://www.hackndev.com
I am in the same situation actually. Or almost, as I'll have only
anonymous users.
I though about restricting votes based on IP addresses, but today,
with NATs and all, that would be unfair for a lot of people.
What I was planning to do is use the session framework. I will have in
the sessions each poll the user has answered.
Of course, a user could erase the cookies and vote again, but the idea
is to avoid accidental voting and the temptation of easy cheating :-)
But I am sure there must be a better way.
Enjoy,
G
What I did was create an additional model for submitted polls. It has:
class SubmittedPoll(models.Model):
poll = models.ForeignKey(Poll)
user = models.ForeignKey(User)
choice = models.ForeignKey(Choice)
submit_date = models.DateTimeField()
As I said, I still have not been able to handle the anonymous user, so
I'm hoping someone can shed some light on a way to do with with
sessions/cookies.
Thanks,
Andy
The idea is to put a cookie in the computer of the other person, where
it stocks all the polls it has participated to. That way it does not
depend of the IP.
The code:
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
voted_polls=request.session.get('has_voted_poll',[])
if poll_id in voted_polls:
return render_to_response('sysvortex/polls/poll_results.html', {
'object': p,
'error_message': "You have already voted.",
})
if p.is_open == False :
# Display the poll results.
return render_to_response('sysvortex/polls/poll_results.html', {
'object': p,
'error_message': "The poll is closed.",
})
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render_to_response('sysvortex/polls/poll_detail.html', {
'object': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
request.session['has_voted_poll']=voted_polls+[poll_id]
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect('/polls/%s/results/' % p.id)
Any comment and improvement welcomed.
Enjoy,
G