from django.shortcuts import render from . forms import VoterRegistrationForm from . models import * # Create your views here. def index(request): voter_registration_form = VoterRegistrationForm() if request.method == 'POST': voter_registration_form = VoterRegistrationForm(request.POST) if voter_registration_form.is_valid(): voter_info = voter_registration_form.cleaned_data zip_code = ZipCode.objects.filter(zip=voter_info['zip_code']).first() if zip_code: # Check if voter exists and if not add them to the database 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() if voter is None: voter = Voter(first_name=voter_info['first_name'], last_name=voter_info['last_name'], age_range=voter_info['age_range'], zip_code=zip_code) voter.save() # Extract questions from the form post questions = dict() for key in request.POST: if key != "first_name" and key != "last_name" and key != "age_range" and key != "zip_code" and key != "csrfmiddlewaretoken": # Check if each question_id is valid question = Question.objects.filter(question_id=key).first() value = request.POST[key] if question: if value == "yes": value = True if value == "no": value = False questions[question] = value # Check if voter has already voted on this question for question in questions: print(question) voter_question = VoterQuestion.objects.filter(voter=voter, question=question).first() if voter_question is None: # Add the voter to the VoterQuestion table voter_question = VoterQuestion(voter=voter, question=question) voter_question.save() # Add the vote to the Vote table vote = Vote(question=question, vote=questions[question]) vote.save() # Redirect to the results page return render(request, 'vote/results.html') questions = Question.objects.all() context = { 'form': voter_registration_form, 'questions': questions, } return render(request, 'vote/index.html', context=context)