문제

I'm trying to create a simple retriction system so the users can't vote twice on a simple poll (mostly like the example poll in the django tutorial) bit I can't seem to be able to find an approach that I like.

The one that I like the most is having a User FK in the Choice model and add the users there, like this:

models.py

vote = models.ForeignKey(User)

views.py

def vote(request):
    # Some validations and stuff...
    vote.add(request.user)

That way I can restrict the votes to 1 per choice, but I wanted to restrict it to 1 per poll. Imagine the situation: you have a poll that has 5 choices, with this validation, the user can only vote 1 time, but 1 time per choice, which means he/she can vote 5 times.

What would you recommend for making a system that allow only 1 vote per poll? I you need the models or something I'll paste them, it's an opensource project.

도움이 되었습니까?

해결책

On your Poll model, add a ManyToManyField to User, representing which users have voted in which polls. For each poll you want to display, check if this poll is in the current user's list of polls. If it is, do not allow them to vote.

And when the current user votes in a poll, add that poll to the current user's list of polls.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top