[Fixed]-Restrict each user to only vote once (Polls, django, python)

1👍

It looks like you have forgotten to create the voter instance after the user has voted.

def law_yes_vote(request, law_id):
    if Voter.objects.filter(law_id=law_id, user_id=request.user.id).exists():

        return render(request, 'law_detail.html', {
            'law': p,
            'error_message': "Sorry, but you have already voted."
        })

    else:
        p = get_object_or_404(Law, pk=law_id)
        p.yes_votes += 1
        p.save()
        Voter.objects.create(law_id=law_id, user_id=request.user.id)

    return HttpResponseRedirect(reverse('laws:law_results', args=(p.id,)))

You’ll need to update law_no_vote in the same way.

Leave a comment