views.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from django.shortcuts import render
  2. from . forms import VoterRegistrationForm
  3. from . models import *
  4. # Create your views here.
  5. def index(request):
  6. voter_registration_form = VoterRegistrationForm()
  7. if request.method == 'POST':
  8. voter_registration_form = VoterRegistrationForm(request.POST)
  9. if voter_registration_form.is_valid():
  10. voter_info = voter_registration_form.cleaned_data
  11. zip_code = ZipCode.objects.filter(zip=voter_info['zip_code']).first()
  12. if zip_code:
  13. # Check if voter exists and if not add them to the database
  14. voter = Voter.objects.filter(first_name=voter_info['first_name'], last_name=voter_info['last_name'], age_range=voter_info['age_range'], zip_code=zip_code).first()
  15. if voter is None:
  16. voter = Voter(first_name=voter_info['first_name'], last_name=voter_info['last_name'], age_range=voter_info['age_range'], zip_code=zip_code)
  17. voter.save()
  18. # Extract questions from the form post
  19. questions = dict()
  20. for key in request.POST:
  21. if key != "first_name" and key != "last_name" and key != "age_range" and key != "zip_code" and key != "csrfmiddlewaretoken":
  22. # Check if each question_id is valid
  23. question = Question.objects.filter(question_id=key).first()
  24. value = request.POST[key]
  25. if question:
  26. if value == "yes":
  27. value = True
  28. if value == "no":
  29. value = False
  30. questions[question] = value
  31. # Check if voter has already voted on this question
  32. for question in questions:
  33. voter_question = VoterQuestion.objects.filter(voter=voter, question=question).first()
  34. if voter_question is None:
  35. # Add the voter to the VoterQuestion table
  36. voter_question = VoterQuestion(voter=voter, question=question)
  37. voter_question.save()
  38. # Add the vote to the Vote table
  39. vote = Vote(question=question, vote=questions[question])
  40. vote.save()
  41. # Redirect to the results page
  42. return render(request, 'vote/thankyou.html')
  43. questions = Question.objects.all()
  44. context = {
  45. 'form': voter_registration_form,
  46. 'questions': questions,
  47. }
  48. return render(request, 'vote/index.html', context=context)
  49. def results(request):
  50. # Tally the votes for each question
  51. questions = Question.objects.all()
  52. for question in questions:
  53. yes_votes = Vote.objects.filter(question=question, vote=True).count()
  54. no_votes = Vote.objects.filter(question=question, vote=False).count()
  55. question.total_votes = yes_votes + no_votes
  56. question.yes_votes = yes_votes
  57. question.no_votes = no_votes
  58. context = {
  59. 'questions': questions,
  60. }
  61. return render(request, 'vote/results.html', context=context)