Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import base64
- from django.utils import timezone
- from datetime import datetime
- from django.shortcuts import render
- from django.views.generic import TemplateView, FormView, View, UpdateView, ListView, DetailView
- from django.contrib.auth import login, logout, authenticate
- from django.core.mail import send_mail
- from django.http.response import HttpResponseRedirect
- from django.core.cache import cache
- from .forms import UserRegistrationForm, UserLoginForm, VoterCardApplicationForm, PoliticalPartyCreateForm, ConstituencyElectionCandidateNominationForm, ConstituencyElectionVotingStep1Form, ConstituencyElectionVotingStep2Form, ConstituencyElectionVotingStep3Form, ConstituencyElectionVotingForm, UserRegistrationStep3Form
- from .models import VoterCardApplication, User, PoliticalParty, PoliticalPartyMember, Election, ConstituencyElectionDetail, ConstituencyElectionCandidateDetail, VoterCard, ElectionEmailOTP, ElectionMobileOTP, generate_otp_code, ElectionUserVoteDetail, UserRegistrationMobileOTP
- from .mixins import CheckValidVoterMixin, CheckSecurityStep1SuccessMixin, CheckSecurityStep2SuccessMixin, CheckSecurityStep3SuccessMixin
- from .utils import get_election_eligible_to_vote, get_constituency_election_eligible_to_vote, send_sms, send_email_verification_link
- class IndexPage(TemplateView):
- template_name = 'index_page.html'
- def get(self, request, *args, **kwargs):
- if request.user.is_authenticated():
- return HttpResponseRedirect('/home')
- return super(IndexPage, self).get(request, *args, **kwargs)
- class UserRegistrationStep1(FormView):
- form_class = UserRegistrationForm
- template_name = 'user_registration_step1.html'
- def form_valid(self, form):
- user = form.save()
- try:
- send_email_verification_link(user)
- except Exception as e:
- print repr(e) # print exception message
- # perform user login
- authenticated_user = authenticate(username=form.cleaned_data['voter_id'], password=form.cleaned_data['password1'])
- login(self.request, authenticated_user)
- # then redirect to success url
- return super(UserRegistrationStep1, self).form_valid(form)
- def get_success_url(self):
- return '/register/step-2'
- class UserRegistrationStep2(TemplateView):
- template_name = 'user_registration_step2.html'
- def get(self, request, *args, **kwargs):
- if not request.user.is_authenticated():
- return HttpResponseRedirect('/login')
- # send user to step 3 if email already verified
- if request.user.is_email_verified:
- return HttpResponseRedirect('/register/step-3')
- try:
- send_email_verification_link(request.user)
- except Exception as e:
- print repr(e) # print exception message
- return super(UserRegistrationStep2, self).get(request, *args, **kwargs)
- class UserRegistrationStep3(FormView):
- form_class = UserRegistrationStep3Form
- template_name = 'user_registration_step3.html'
- def get(self, request, *args, **kwargs):
- if not request.user.is_authenticated():
- return HttpResponseRedirect('/login')
- # send user to step 2 if email not verified
- if not request.user.is_email_verified:
- return HttpResponseRedirect('/register/step-2')
- # send user to homepage if mobile already verified
- if request.user.is_mobile_number_verified:
- return HttpResponseRedirect('/home')
- try:
- self.send_mobile_otp()
- except Exception as e:
- print repr(e) # print exception message
- return super(UserRegistrationStep3, self).get(request, *args, **kwargs)
- def send_mobile_otp(self):
- mobile_otp_object = UserRegistrationMobileOTP.objects.filter(user=self.request.user).first()
- if not mobile_otp_object:
- mobile_otp_object = UserRegistrationMobileOTP.objects.create(user=self.request.user)
- if not mobile_otp_object.is_otp_valid():
- mobile_otp_object.otp_code = generate_otp_code()
- mobile_otp_object.created_on = timezone.now()
- mobile_otp_object.save()
- otp_message = "Your Mobile OTP to complete registration is {}. It is valid for 30 mins. Please do not share it with anyone.".format(mobile_otp_object.otp_code)
- print otp_message
- try:
- send_sms(
- recipient_mobile_number = '+91'+self.request.user.mobile_number,
- message=otp_message
- )
- print "Mobile OTP sent successfully"
- except Exception as e:
- print repr(e) # print error message
- def get_form_kwargs(self):
- kwargs = super(UserRegistrationStep3, self).get_form_kwargs()
- kwargs['user'] = self.request.user
- return kwargs
- def form_valid(self, form):
- # mark mobile number has been verified
- self.request.user.is_mobile_number_verified = True
- self.request.user.save()
- # then redirect to success url
- return super(UserRegistrationStep3, self).form_valid(form)
- def get_success_url(self):
- return '/user-registration/success?first_name=' + str(self.request.user.first_name)
- class UserRegistrationSuccess(TemplateView):
- template_name = 'user_registration_success.html'
- def get_context_data(self, **kwargs):
- context = super(UserRegistrationSuccess, self).get_context_data(**kwargs)
- context['first_name'] = self.request.GET.get('first_name', '')
- return context
- class LoginView(FormView):
- form_class = UserLoginForm
- template_name = 'login.html'
- success_url = '/home'
- def form_valid(self, form):
- user = form.user
- login(self.request, user)
- # send to user registration step 2 if email is not verified
- if not user.is_email_verified:
- return HttpResponseRedirect('/register/step-2')
- # send to user registration step 3 if mobile number is not verified
- if not user.is_mobile_number_verified:
- return HttpResponseRedirect('/register/step-3')
- # redirect to homepage
- return super(LoginView, self).form_valid(form)
- class LogoutView(TemplateView):
- template_name = 'logout.html'
- def get(self, request, *args, **kwargs):
- logout(request)
- return super(LogoutView, self).get(request, *args, **kwargs)
- class AboutUsPage(TemplateView):
- template_name = 'about_us_page.html'
- class ContactUsPage(TemplateView):
- template_name = 'contact_us_page.html'
- class LoggedInHomePage(TemplateView):
- template_name = 'home_page_loggedin.html'
- def get(self, request, *args, **kwargs):
- if not request.user.is_authenticated():
- return HttpResponseRedirect('/login')
- # send user to step 2 if email not verified
- if not request.user.is_email_verified:
- return HttpResponseRedirect('/register/step-2')
- # send user to step 3 if mobile not verified
- if not request.user.is_mobile_number_verified:
- return HttpResponseRedirect('/register/step-3')
- return super(LoggedInHomePage, self).get(request, *args, **kwargs)
- class VoterCardRegistration(FormView):
- form_class = VoterCardApplicationForm
- template_name = 'voter_card_registration.html'
- def form_valid(self, form):
- # save voter card application form information to the database
- self.voter_card_application = form.save()
- # now send email to applicant with the application id
- subject = "Your application for new voter card has been submitted successfully"
- message = "Thank you "+ self.voter_card_application.first_name + " ! Your application for new voter card registration has been submitted successfully. Your Application ID is " + str(self.voter_card_application.id) + ". \n\nYour application will be processed within one week. \n\nYou can check your application status from the wesite using above application id."
- from_email = 'pinky.1995gupta@gmail.com' # sender ie evoting admin
- recipient_list = [self.voter_card_application.email] # recipients list
- print message
- try:
- send_mail(subject=subject, message=message, from_email=from_email, recipient_list=recipient_list)
- print "Mail sent successfully."
- except Exception as e:
- print repr(e) # print exception message
- # then redirect to success url
- return super(VoterCardRegistration, self).form_valid(form)
- def get_success_url(self):
- return '/voter-card-registration/success?application_id=' + str(self.voter_card_application.id)
- class VoterCardRegistrationSuccess(TemplateView):
- template_name = 'voter_card_registration_success.html'
- def get_context_data(self, **kwargs):
- context = super(VoterCardRegistrationSuccess, self).get_context_data(**kwargs)
- context['application_id'] = self.request.GET.get('application_id', '')
- return context
- class VoterCardRegistrationCheckStatus(View):
- def get(self, request, *args, **kwargs):
- application_id = request.GET.get('application_id')
- # load page with empty form
- if not application_id:
- return render(request, template_name='voter_card_registration_check_status.html', context={})
- # try to fetch application from database using application id
- try:
- application = VoterCardApplication.objects.get(id=int(application_id))
- except:
- # load page with empty form if invalid application id
- return render(request, template_name='voter_card_registration_check_status.html', context={})
- # redisplay page with application status
- context = {'application_status':application.application_status, 'application_id':application_id}
- return render(request, template_name='voter_card_registration_check_status.html', context=context)
- class VoterCardRegistrationEditApplication(UpdateView):
- model = VoterCardApplication
- form_class = VoterCardApplicationForm
- template_name = 'voter_card_application_edit.html'
- def form_valid(self, form):
- self.voter_card_application = form.save()
- # set status of application as re-opened
- self.voter_card_application.application_status = 4
- self.voter_card_application.save()
- return super(VoterCardRegistrationEditApplication, self).form_valid(form)
- def get_success_url(self):
- return '/voter-card-registration/success?application_id=' + str(self.voter_card_application.id)
- class UserEmailVerificationView(TemplateView):
- template_name = 'user_email_verification.html'
- def get_context_data(self, **kwargs):
- context = super(UserEmailVerificationView, self).get_context_data(**kwargs)
- token = self.request.GET.get('token', '')
- email = base64.urlsafe_b64decode(str(token)) # decode token to get email
- user = User.objects.filter(email=email).first() # get user
- if user:
- user.is_email_verified = True # mark email as verified
- user.save()
- context['email_verified'] = True
- context['email'] = user.email
- else:
- context['email_verified'] = False
- return context
- class PoliticalPartiesListView(ListView):
- template_name = 'political_parties_list.html'
- def get_queryset(self):
- return PoliticalParty.objects.filter(is_approved=True)
- class PoliticalPartiesCreateView(FormView):
- form_class = PoliticalPartyCreateForm
- template_name = 'political_party_create_page.html'
- success_url = '/political-parties'
- def form_valid(self, form):
- political_party = form.save(commit=False)
- political_party.created_by = self.request.user
- political_party.save()
- return super(PoliticalPartiesCreateView, self).form_valid(form)
- class PoliticalPartiesDetailView(DetailView):
- model = PoliticalParty
- template_name = 'political_party_detail.html'
- def get_context_data(self, **kwargs):
- context = super(PoliticalPartiesDetailView, self).get_context_data(**kwargs)
- context['political_party_member'] = PoliticalPartyMember.objects.filter(political_party=context['object'], user=self.request.user).first()
- return context
- class PoliticalPartyJoinView(View):
- def get(self, request, *args, **kwargs):
- political_party = PoliticalParty.objects.filter(id=kwargs['pk']).first()
- if not political_party:
- return HttpResponseRedirect('/political-parties')
- # create user a member of political party
- PoliticalPartyMember.objects.filter(user=request.user).delete() # delete old membership
- PoliticalPartyMember.objects.create(political_party=political_party, user=request.user)
- return HttpResponseRedirect('/political-parties/{}'.format(kwargs['pk']))
- class PoliticalPartyUnjoinView(View):
- def get(self, request, *args, **kwargs):
- political_party = PoliticalParty.objects.filter(id=kwargs['pk']).first()
- if not political_party:
- return HttpResponseRedirect('/political-parties')
- # remove user from political party members
- PoliticalPartyMember.objects.filter(user=request.user).delete()
- return HttpResponseRedirect('/political-parties/{}'.format(kwargs['pk']))
- class CurrentElectionsView(TemplateView):
- template_name = 'current_elections_page.html'
- def get_context_data(self, **kwargs):
- context = super(CurrentElectionsView, self).get_context_data(**kwargs)
- now = timezone.now()
- context['ongoing_elections'] = Election.objects.filter(start_date__lte=now, end_date__gte=now)
- context['eligible_election_to_vote'] = get_election_eligible_to_vote(self.request.user)
- return context
- class PastElectionsView(TemplateView):
- template_name = 'past_elections_page.html'
- def get_context_data(self, **kwargs):
- context = super(PastElectionsView, self).get_context_data(**kwargs)
- now = timezone.now()
- context['past_elections'] = Election.objects.filter(end_date__lt=now)
- return context
- class UpcomingElectionsView(TemplateView):
- template_name = 'upcoming_elections_page.html'
- def get_context_data(self, **kwargs):
- context = super(UpcomingElectionsView, self).get_context_data(**kwargs)
- now = timezone.now()
- context['upcoming_elections'] = Election.objects.filter(start_date__gt=now)
- return context
- class ElectionDetailView(DetailView):
- model = Election
- template_name = 'election_detail_page.html'
- def get_context_data(self, **kwargs):
- context = super(ElectionDetailView, self).get_context_data(**kwargs)
- context['eligible_constituency_election_to_vote'] = get_constituency_election_eligible_to_vote(self.request.user)
- return context
- class ConstituencyElectionDetailView(DetailView):
- template_name = 'constituency_election_detail_page.html'
- def get_queryset(self):
- return ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'])
- def get_context_data(self, **kwargs):
- context = super(ConstituencyElectionDetailView, self).get_context_data(**kwargs)
- context['nominated_in_other_constituency'] = ConstituencyElectionCandidateDetail.objects.exclude(constituency_election=context['object']).filter(constituency_election__election=context['object'].election, candidate=self.request.user).first()
- context['candidate_application'] = ConstituencyElectionCandidateDetail.objects.filter(constituency_election=context['object'], candidate=self.request.user).first()
- candidates = list(ConstituencyElectionCandidateDetail.objects.filter(constituency_election=context['object'], nomination_status=1))
- context['candidates'] = candidates
- # compute the winner if election is over
- if context['object'].election.get_election_status() == "Over":
- votes_received_list = [candidate.votes_received for candidate in candidates]
- if votes_received_list:
- max_votes_recieved = max(votes_received_list)
- if max_votes_recieved > 0:
- max_votes_candidate_index = votes_received_list.index(max_votes_recieved)
- winner_candidate = candidates[max_votes_candidate_index]
- context['winner_candidate'] = winner_candidate
- if context['object'] == get_constituency_election_eligible_to_vote(self.request.user):
- context['voting_link'] = '/elections/{}/{}/vote/security-step-1'.format(self.kwargs['election_id'], self.kwargs['pk'])
- return context
- class ConstituencyElectionCandidateNominationView(FormView):
- form_class = ConstituencyElectionCandidateNominationForm
- template_name = 'constituency_election_candidate_nomination_form_page.html'
- def get_context_data(self, **kwargs):
- context = super(ConstituencyElectionCandidateNominationView, self).get_context_data(**kwargs)
- # add constituency election object to context
- context['constituency_election_obj'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
- return context
- def form_valid(self, form):
- candidate_nomination = form.save(commit=False)
- # set other required fields
- candidate_nomination.constituency_election_id = self.kwargs['pk']
- candidate_nomination.candidate = self.request.user
- candidate_nomination.save()
- redirect_url = '/elections/{}/{}'.format(self.kwargs['election_id'], self.kwargs['pk'])
- return HttpResponseRedirect(redirect_url)
- class ConstituencyElectionCandidateNominationDeleteView(View):
- def get(self, request, *args, **kwargs):
- ConstituencyElectionCandidateDetail.objects.filter(constituency_election_id=self.kwargs['pk'], candidate=self.request.user).delete()
- redirect_url = '/elections/{}/{}'.format(self.kwargs['election_id'], self.kwargs['pk'])
- return HttpResponseRedirect(redirect_url)
- class ConstituencyElectionCandidateDetailView(DetailView):
- template_name = 'constituency_election_candidate_detail_page.html'
- def get_queryset(self):
- return ConstituencyElectionCandidateDetail.objects.filter(constituency_election_id=self.kwargs['constituency_election_id'])
- ##Voting Views
- class ConstituencyElectionVotingStep1(CheckValidVoterMixin, FormView):
- form_class = ConstituencyElectionVotingStep1Form
- template_name = 'election_voting_step1.html'
- def get_context_data(self, **kwargs):
- context = super(ConstituencyElectionVotingStep1, self).get_context_data(**kwargs)
- # add constituency election object to context
- context['constituency_election_obj'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
- return context
- def get_form_kwargs(self):
- kwargs = super(ConstituencyElectionVotingStep1, self).get_form_kwargs()
- kwargs['user'] = self.request.user
- return kwargs
- def send_email_otp(self):
- email_otp_object = ElectionEmailOTP.objects.filter(constituency_election_id=self.kwargs['pk'], user=self.request.user).first()
- if not email_otp_object:
- email_otp_object = ElectionEmailOTP.objects.create(constituency_election_id=self.kwargs['pk'], user=self.request.user)
- if not email_otp_object.is_otp_valid():
- email_otp_object.otp_code = generate_otp_code()
- email_otp_object.created_on = timezone.now()
- email_otp_object.save()
- otp_message = "Your Email OTP to vote is {}. It is valid for 15 mins. Please do not share it with anyone.".format(email_otp_object.otp_code)
- print otp_message
- try:
- send_mail(subject='Email OTP for Voting', message=otp_message, from_email='pinky.1995gupta@gmail.com', recipient_list=[self.request.user.email])
- print "Email OTP sent successfully"
- except Exception as e:
- print repr(e) # print error message
- def form_valid(self, form):
- # set step-1 success flag
- self.request.session['{}_voting_step1_success'.format(self.request.user.id)] = True
- # send email otp
- self.send_email_otp()
- redirect_url = '/elections/{}/{}/vote/security-step-2'.format(self.kwargs['election_id'], self.kwargs['pk'])
- return HttpResponseRedirect(redirect_url)
- class ConstituencyElectionVotingStep2(CheckValidVoterMixin, CheckSecurityStep1SuccessMixin, FormView):
- form_class = ConstituencyElectionVotingStep2Form
- template_name = 'election_voting_step2.html'
- def get_context_data(self, **kwargs):
- context = super(ConstituencyElectionVotingStep2, self).get_context_data(**kwargs)
- # add constituency election object to context
- context['constituency_election_obj'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
- return context
- def get_form_kwargs(self):
- kwargs = super(ConstituencyElectionVotingStep2, self).get_form_kwargs()
- kwargs['user'] = self.request.user
- kwargs['constituency_election'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
- return kwargs
- def send_mobile_otp(self):
- mobile_otp_object = ElectionMobileOTP.objects.filter(constituency_election_id=self.kwargs['pk'], user=self.request.user).first()
- if not mobile_otp_object:
- mobile_otp_object = ElectionMobileOTP.objects.create(constituency_election_id=self.kwargs['pk'], user=self.request.user)
- if not mobile_otp_object.is_otp_valid():
- mobile_otp_object.otp_code = generate_otp_code()
- mobile_otp_object.created_on = timezone.now()
- mobile_otp_object.save()
- otp_message = "Your Mobile OTP to vote is {}. It is valid for 15 mins. Please do not share it with anyone.".format(mobile_otp_object.otp_code)
- print otp_message
- try:
- send_sms(
- recipient_mobile_number = '+91'+self.request.user.mobile_number,
- message=otp_message
- )
- print "Mobile OTP sent successfully"
- except Exception as e:
- print repr(e) # print error message
- def form_valid(self, form):
- # set step-2 success flag
- self.request.session['{}_voting_step2_success'.format(self.request.user.id)] = True
- # send mobile otp
- self.send_mobile_otp()
- redirect_url = '/elections/{}/{}/vote/security-step-3'.format(self.kwargs['election_id'], self.kwargs['pk'])
- return HttpResponseRedirect(redirect_url)
- class ConstituencyElectionVotingStep3(CheckValidVoterMixin, CheckSecurityStep1SuccessMixin, CheckSecurityStep2SuccessMixin, FormView):
- form_class = ConstituencyElectionVotingStep3Form
- template_name = 'election_voting_step3.html'
- def get_context_data(self, **kwargs):
- context = super(ConstituencyElectionVotingStep3, self).get_context_data(**kwargs)
- # add constituency election object to context
- context['constituency_election_obj'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
- return context
- def get_form_kwargs(self):
- kwargs = super(ConstituencyElectionVotingStep3, self).get_form_kwargs()
- kwargs['user'] = self.request.user
- kwargs['constituency_election'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
- return kwargs
- def form_valid(self, form):
- # set step-3 success flag
- self.request.session['{}_voting_step3_success'.format(self.request.user.id)] = True
- redirect_url = '/elections/{}/{}/vote'.format(self.kwargs['election_id'], self.kwargs['pk'])
- return HttpResponseRedirect(redirect_url)
- class ConstituencyElectionVotingView(CheckValidVoterMixin, CheckSecurityStep1SuccessMixin, CheckSecurityStep2SuccessMixin, CheckSecurityStep3SuccessMixin, FormView):
- form_class = ConstituencyElectionVotingForm
- template_name = 'election_voting_page.html'
- def get_context_data(self, **kwargs):
- context = super(ConstituencyElectionVotingView, self).get_context_data(**kwargs)
- # add constituency election object to context
- context['constituency_election_obj'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
- context['candidates'] = ConstituencyElectionCandidateDetail.objects.filter(constituency_election_id=self.kwargs['pk'], nomination_status=1)
- return context
- def get_form_kwargs(self):
- kwargs = super(ConstituencyElectionVotingView, self).get_form_kwargs()
- kwargs['user'] = self.request.user
- kwargs['constituency_election'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
- return kwargs
- def form_valid(self, form):
- # save vote
- selected_candidate = ConstituencyElectionCandidateDetail.objects.filter(constituency_election_id=self.kwargs['pk'], nomination_status=1, id=form.cleaned_data['constituency_election_candidate']).first()
- selected_candidate.votes_received += 1
- selected_candidate.save()
- # save that user has voted in this election
- ElectionUserVoteDetail.objects.create(user=self.request.user, election=selected_candidate.constituency_election.election)
- redirect_url = '/elections/{}/{}/vote/thanks'.format(self.kwargs['election_id'], self.kwargs['pk'])
- return HttpResponseRedirect(redirect_url)
- class ConstituencyElectionVotingSuccessView(TemplateView):
- template_name = 'election_voting_success.html'
- def get_context_data(self, **kwargs):
- context = super(ConstituencyElectionVotingSuccessView, self).get_context_data(**kwargs)
- # add constituency election object to context
- context['constituency_election_obj'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
- return context
Add Comment
Please, Sign In to add comment