views.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. print(question)
  34. voter_question = VoterQuestion.objects.filter(voter=voter, question=question).first()
  35. if voter_question is None:
  36. # Add the voter to the VoterQuestion table
  37. voter_question = VoterQuestion(voter=voter, question=question)
  38. voter_question.save()
  39. # Add the vote to the Vote table
  40. vote = Vote(question=question, vote=questions[question])
  41. vote.save()
  42. # Redirect to the results page
  43. return render(request, 'vote/results.html')
  44. questions = Question.objects.all()
  45. context = {
  46. 'form': voter_registration_form,
  47. 'questions': questions,
  48. }
  49. return render(request, 'vote/index.html', context=context)