Meetu Agarwal
Meetu Agarwal

Reputation: 59

Why does django tutorial allow users to vote multiple times on a poll? How can I fix it?

I have been following the django tutorial for building the polls application and I don't understand why would an application allow users to vote multiple times on a poll.

Upvotes: 1

Views: 511

Answers (1)

bakkal
bakkal

Reputation: 55448

Why

Well, it is more complicated to implement what you described, and for a tutorial, you want simple code. This also requires authentication to identify the user, to get the request.user value that I'll use below (a value that isn't always available unless e.g. the view is set to login_required)

How to fix

With the models in the tutorial, I'm afraid it's not possible to do that, because when a user votes, all that happens is a selected_choice += 1 operation, which as you can see, does not log the user.

If you wanted to log the user in a vote, you'd have to create a model to do that, e.g.

class Vote(Model):
    question = ForeignKey(Question)
    selected_choice = ForeignKey(Choice)
    user = ForeignKey(User)

    class Meta:
        unique_together = (
            ('question', 'user'),
        )

Having a unique_together like the above makes sure our database can only one choice vote per user per question

Here's some pseudo code on how to handle a vote action

def vote(request, question_id):
    user = request.user
    question = get_object_or_404(Question, pk=question_id)
    selected_choice = question.choice_set.get(pk=request.POST['choice'])

    # Update the vote info, or create if doesn't exist yet 
    Vote.objects.update_or_create(
        user=user,
        question=question,
        defaults={'selected_choice': selected_choice}
    )

    # Recalculate the select choice counts for the question
    # For the question, set each question.choice to the count

Upvotes: 1

Related Questions