Guest User

Untitled

a guest
May 24th, 2017
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 26.51 KB | None | 0 0
  1. import base64
  2. from django.utils import timezone
  3. from datetime import datetime
  4.  
  5. from django.shortcuts import render
  6. from django.views.generic import TemplateView, FormView, View, UpdateView, ListView, DetailView
  7. from django.contrib.auth import login, logout, authenticate
  8. from django.core.mail import send_mail
  9. from django.http.response import HttpResponseRedirect
  10. from django.core.cache import cache
  11.  
  12. from .forms import UserRegistrationForm, UserLoginForm, VoterCardApplicationForm, PoliticalPartyCreateForm, ConstituencyElectionCandidateNominationForm, ConstituencyElectionVotingStep1Form, ConstituencyElectionVotingStep2Form, ConstituencyElectionVotingStep3Form, ConstituencyElectionVotingForm, UserRegistrationStep3Form
  13. from .models import VoterCardApplication, User, PoliticalParty, PoliticalPartyMember, Election, ConstituencyElectionDetail, ConstituencyElectionCandidateDetail, VoterCard, ElectionEmailOTP, ElectionMobileOTP, generate_otp_code, ElectionUserVoteDetail, UserRegistrationMobileOTP
  14. from .mixins import CheckValidVoterMixin, CheckSecurityStep1SuccessMixin, CheckSecurityStep2SuccessMixin, CheckSecurityStep3SuccessMixin
  15. from .utils import get_election_eligible_to_vote, get_constituency_election_eligible_to_vote, send_sms, send_email_verification_link
  16.  
  17.  
  18. class IndexPage(TemplateView):
  19.  
  20. template_name = 'index_page.html'
  21.  
  22. def get(self, request, *args, **kwargs):
  23. if request.user.is_authenticated():
  24. return HttpResponseRedirect('/home')
  25.  
  26. return super(IndexPage, self).get(request, *args, **kwargs)
  27.  
  28.  
  29. class UserRegistrationStep1(FormView):
  30.  
  31. form_class = UserRegistrationForm
  32. template_name = 'user_registration_step1.html'
  33.  
  34. def form_valid(self, form):
  35. user = form.save()
  36.  
  37. try:
  38. send_email_verification_link(user)
  39. except Exception as e:
  40. print repr(e) # print exception message
  41.  
  42. # perform user login
  43. authenticated_user = authenticate(username=form.cleaned_data['voter_id'], password=form.cleaned_data['password1'])
  44. login(self.request, authenticated_user)
  45.  
  46. # then redirect to success url
  47. return super(UserRegistrationStep1, self).form_valid(form)
  48.  
  49. def get_success_url(self):
  50. return '/register/step-2'
  51.  
  52.  
  53. class UserRegistrationStep2(TemplateView):
  54.  
  55. template_name = 'user_registration_step2.html'
  56.  
  57. def get(self, request, *args, **kwargs):
  58. if not request.user.is_authenticated():
  59. return HttpResponseRedirect('/login')
  60.  
  61. # send user to step 3 if email already verified
  62. if request.user.is_email_verified:
  63. return HttpResponseRedirect('/register/step-3')
  64.  
  65. try:
  66. send_email_verification_link(request.user)
  67. except Exception as e:
  68. print repr(e) # print exception message
  69.  
  70. return super(UserRegistrationStep2, self).get(request, *args, **kwargs)
  71.  
  72.  
  73. class UserRegistrationStep3(FormView):
  74.  
  75. form_class = UserRegistrationStep3Form
  76. template_name = 'user_registration_step3.html'
  77.  
  78. def get(self, request, *args, **kwargs):
  79. if not request.user.is_authenticated():
  80. return HttpResponseRedirect('/login')
  81.  
  82. # send user to step 2 if email not verified
  83. if not request.user.is_email_verified:
  84. return HttpResponseRedirect('/register/step-2')
  85.  
  86. # send user to homepage if mobile already verified
  87. if request.user.is_mobile_number_verified:
  88. return HttpResponseRedirect('/home')
  89.  
  90. try:
  91. self.send_mobile_otp()
  92. except Exception as e:
  93. print repr(e) # print exception message
  94.  
  95. return super(UserRegistrationStep3, self).get(request, *args, **kwargs)
  96.  
  97. def send_mobile_otp(self):
  98. mobile_otp_object = UserRegistrationMobileOTP.objects.filter(user=self.request.user).first()
  99. if not mobile_otp_object:
  100. mobile_otp_object = UserRegistrationMobileOTP.objects.create(user=self.request.user)
  101.  
  102. if not mobile_otp_object.is_otp_valid():
  103. mobile_otp_object.otp_code = generate_otp_code()
  104. mobile_otp_object.created_on = timezone.now()
  105. mobile_otp_object.save()
  106.  
  107. 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)
  108. print otp_message
  109.  
  110. try:
  111. send_sms(
  112. recipient_mobile_number = '+91'+self.request.user.mobile_number,
  113. message=otp_message
  114. )
  115. print "Mobile OTP sent successfully"
  116. except Exception as e:
  117. print repr(e) # print error message
  118.  
  119. def get_form_kwargs(self):
  120. kwargs = super(UserRegistrationStep3, self).get_form_kwargs()
  121. kwargs['user'] = self.request.user
  122. return kwargs
  123.  
  124. def form_valid(self, form):
  125. # mark mobile number has been verified
  126. self.request.user.is_mobile_number_verified = True
  127. self.request.user.save()
  128.  
  129. # then redirect to success url
  130. return super(UserRegistrationStep3, self).form_valid(form)
  131.  
  132. def get_success_url(self):
  133. return '/user-registration/success?first_name=' + str(self.request.user.first_name)
  134.  
  135.  
  136. class UserRegistrationSuccess(TemplateView):
  137.  
  138. template_name = 'user_registration_success.html'
  139.  
  140. def get_context_data(self, **kwargs):
  141. context = super(UserRegistrationSuccess, self).get_context_data(**kwargs)
  142. context['first_name'] = self.request.GET.get('first_name', '')
  143. return context
  144.  
  145.  
  146. class LoginView(FormView):
  147.  
  148. form_class = UserLoginForm
  149. template_name = 'login.html'
  150. success_url = '/home'
  151.  
  152. def form_valid(self, form):
  153. user = form.user
  154.  
  155. login(self.request, user)
  156.  
  157. # send to user registration step 2 if email is not verified
  158. if not user.is_email_verified:
  159. return HttpResponseRedirect('/register/step-2')
  160.  
  161. # send to user registration step 3 if mobile number is not verified
  162. if not user.is_mobile_number_verified:
  163. return HttpResponseRedirect('/register/step-3')
  164.  
  165. # redirect to homepage
  166. return super(LoginView, self).form_valid(form)
  167.  
  168.  
  169. class LogoutView(TemplateView):
  170.  
  171. template_name = 'logout.html'
  172.  
  173. def get(self, request, *args, **kwargs):
  174. logout(request)
  175. return super(LogoutView, self).get(request, *args, **kwargs)
  176.  
  177.  
  178. class AboutUsPage(TemplateView):
  179.  
  180. template_name = 'about_us_page.html'
  181.  
  182.  
  183. class ContactUsPage(TemplateView):
  184.  
  185. template_name = 'contact_us_page.html'
  186.  
  187.  
  188. class LoggedInHomePage(TemplateView):
  189.  
  190. template_name = 'home_page_loggedin.html'
  191.  
  192. def get(self, request, *args, **kwargs):
  193. if not request.user.is_authenticated():
  194. return HttpResponseRedirect('/login')
  195.  
  196. # send user to step 2 if email not verified
  197. if not request.user.is_email_verified:
  198. return HttpResponseRedirect('/register/step-2')
  199.  
  200. # send user to step 3 if mobile not verified
  201. if not request.user.is_mobile_number_verified:
  202. return HttpResponseRedirect('/register/step-3')
  203.  
  204. return super(LoggedInHomePage, self).get(request, *args, **kwargs)
  205.  
  206.  
  207. class VoterCardRegistration(FormView):
  208. form_class = VoterCardApplicationForm
  209. template_name = 'voter_card_registration.html'
  210.  
  211. def form_valid(self, form):
  212. # save voter card application form information to the database
  213. self.voter_card_application = form.save()
  214.  
  215. # now send email to applicant with the application id
  216. subject = "Your application for new voter card has been submitted successfully"
  217. 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."
  218. from_email = 'pinky.1995gupta@gmail.com' # sender ie evoting admin
  219. recipient_list = [self.voter_card_application.email] # recipients list
  220.  
  221. print message
  222.  
  223. try:
  224. send_mail(subject=subject, message=message, from_email=from_email, recipient_list=recipient_list)
  225. print "Mail sent successfully."
  226. except Exception as e:
  227. print repr(e) # print exception message
  228.  
  229. # then redirect to success url
  230. return super(VoterCardRegistration, self).form_valid(form)
  231.  
  232. def get_success_url(self):
  233. return '/voter-card-registration/success?application_id=' + str(self.voter_card_application.id)
  234.  
  235.  
  236. class VoterCardRegistrationSuccess(TemplateView):
  237.  
  238. template_name = 'voter_card_registration_success.html'
  239.  
  240. def get_context_data(self, **kwargs):
  241. context = super(VoterCardRegistrationSuccess, self).get_context_data(**kwargs)
  242. context['application_id'] = self.request.GET.get('application_id', '')
  243. return context
  244.  
  245.  
  246. class VoterCardRegistrationCheckStatus(View):
  247.  
  248. def get(self, request, *args, **kwargs):
  249. application_id = request.GET.get('application_id')
  250.  
  251. # load page with empty form
  252. if not application_id:
  253. return render(request, template_name='voter_card_registration_check_status.html', context={})
  254.  
  255. # try to fetch application from database using application id
  256. try:
  257. application = VoterCardApplication.objects.get(id=int(application_id))
  258. except:
  259. # load page with empty form if invalid application id
  260. return render(request, template_name='voter_card_registration_check_status.html', context={})
  261.  
  262. # redisplay page with application status
  263. context = {'application_status':application.application_status, 'application_id':application_id}
  264. return render(request, template_name='voter_card_registration_check_status.html', context=context)
  265.  
  266.  
  267. class VoterCardRegistrationEditApplication(UpdateView):
  268.  
  269. model = VoterCardApplication
  270. form_class = VoterCardApplicationForm
  271. template_name = 'voter_card_application_edit.html'
  272.  
  273. def form_valid(self, form):
  274. self.voter_card_application = form.save()
  275.  
  276. # set status of application as re-opened
  277. self.voter_card_application.application_status = 4
  278. self.voter_card_application.save()
  279.  
  280. return super(VoterCardRegistrationEditApplication, self).form_valid(form)
  281.  
  282. def get_success_url(self):
  283. return '/voter-card-registration/success?application_id=' + str(self.voter_card_application.id)
  284.  
  285.  
  286. class UserEmailVerificationView(TemplateView):
  287.  
  288. template_name = 'user_email_verification.html'
  289.  
  290. def get_context_data(self, **kwargs):
  291. context = super(UserEmailVerificationView, self).get_context_data(**kwargs)
  292. token = self.request.GET.get('token', '')
  293.  
  294. email = base64.urlsafe_b64decode(str(token)) # decode token to get email
  295. user = User.objects.filter(email=email).first() # get user
  296.  
  297. if user:
  298. user.is_email_verified = True # mark email as verified
  299. user.save()
  300. context['email_verified'] = True
  301. context['email'] = user.email
  302. else:
  303. context['email_verified'] = False
  304.  
  305. return context
  306.  
  307.  
  308. class PoliticalPartiesListView(ListView):
  309.  
  310. template_name = 'political_parties_list.html'
  311.  
  312. def get_queryset(self):
  313. return PoliticalParty.objects.filter(is_approved=True)
  314.  
  315.  
  316. class PoliticalPartiesCreateView(FormView):
  317.  
  318. form_class = PoliticalPartyCreateForm
  319. template_name = 'political_party_create_page.html'
  320. success_url = '/political-parties'
  321.  
  322. def form_valid(self, form):
  323. political_party = form.save(commit=False)
  324. political_party.created_by = self.request.user
  325. political_party.save()
  326. return super(PoliticalPartiesCreateView, self).form_valid(form)
  327.  
  328.  
  329. class PoliticalPartiesDetailView(DetailView):
  330.  
  331. model = PoliticalParty
  332. template_name = 'political_party_detail.html'
  333.  
  334. def get_context_data(self, **kwargs):
  335. context = super(PoliticalPartiesDetailView, self).get_context_data(**kwargs)
  336. context['political_party_member'] = PoliticalPartyMember.objects.filter(political_party=context['object'], user=self.request.user).first()
  337. return context
  338.  
  339.  
  340. class PoliticalPartyJoinView(View):
  341.  
  342. def get(self, request, *args, **kwargs):
  343. political_party = PoliticalParty.objects.filter(id=kwargs['pk']).first()
  344.  
  345. if not political_party:
  346. return HttpResponseRedirect('/political-parties')
  347.  
  348. # create user a member of political party
  349. PoliticalPartyMember.objects.filter(user=request.user).delete() # delete old membership
  350. PoliticalPartyMember.objects.create(political_party=political_party, user=request.user)
  351.  
  352. return HttpResponseRedirect('/political-parties/{}'.format(kwargs['pk']))
  353.  
  354.  
  355. class PoliticalPartyUnjoinView(View):
  356.  
  357. def get(self, request, *args, **kwargs):
  358. political_party = PoliticalParty.objects.filter(id=kwargs['pk']).first()
  359.  
  360. if not political_party:
  361. return HttpResponseRedirect('/political-parties')
  362.  
  363. # remove user from political party members
  364. PoliticalPartyMember.objects.filter(user=request.user).delete()
  365.  
  366. return HttpResponseRedirect('/political-parties/{}'.format(kwargs['pk']))
  367.  
  368.  
  369. class CurrentElectionsView(TemplateView):
  370.  
  371. template_name = 'current_elections_page.html'
  372.  
  373. def get_context_data(self, **kwargs):
  374. context = super(CurrentElectionsView, self).get_context_data(**kwargs)
  375. now = timezone.now()
  376. context['ongoing_elections'] = Election.objects.filter(start_date__lte=now, end_date__gte=now)
  377. context['eligible_election_to_vote'] = get_election_eligible_to_vote(self.request.user)
  378. return context
  379.  
  380.  
  381. class PastElectionsView(TemplateView):
  382.  
  383. template_name = 'past_elections_page.html'
  384.  
  385. def get_context_data(self, **kwargs):
  386. context = super(PastElectionsView, self).get_context_data(**kwargs)
  387. now = timezone.now()
  388. context['past_elections'] = Election.objects.filter(end_date__lt=now)
  389. return context
  390.  
  391.  
  392. class UpcomingElectionsView(TemplateView):
  393.  
  394. template_name = 'upcoming_elections_page.html'
  395.  
  396. def get_context_data(self, **kwargs):
  397. context = super(UpcomingElectionsView, self).get_context_data(**kwargs)
  398. now = timezone.now()
  399. context['upcoming_elections'] = Election.objects.filter(start_date__gt=now)
  400. return context
  401.  
  402.  
  403. class ElectionDetailView(DetailView):
  404.  
  405. model = Election
  406. template_name = 'election_detail_page.html'
  407.  
  408. def get_context_data(self, **kwargs):
  409. context = super(ElectionDetailView, self).get_context_data(**kwargs)
  410.  
  411. context['eligible_constituency_election_to_vote'] = get_constituency_election_eligible_to_vote(self.request.user)
  412.  
  413. return context
  414.  
  415.  
  416. class ConstituencyElectionDetailView(DetailView):
  417.  
  418. template_name = 'constituency_election_detail_page.html'
  419.  
  420. def get_queryset(self):
  421. return ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'])
  422.  
  423. def get_context_data(self, **kwargs):
  424. context = super(ConstituencyElectionDetailView, self).get_context_data(**kwargs)
  425.  
  426. context['nominated_in_other_constituency'] = ConstituencyElectionCandidateDetail.objects.exclude(constituency_election=context['object']).filter(constituency_election__election=context['object'].election, candidate=self.request.user).first()
  427. context['candidate_application'] = ConstituencyElectionCandidateDetail.objects.filter(constituency_election=context['object'], candidate=self.request.user).first()
  428.  
  429. candidates = list(ConstituencyElectionCandidateDetail.objects.filter(constituency_election=context['object'], nomination_status=1))
  430. context['candidates'] = candidates
  431.  
  432. # compute the winner if election is over
  433. if context['object'].election.get_election_status() == "Over":
  434. votes_received_list = [candidate.votes_received for candidate in candidates]
  435. if votes_received_list:
  436. max_votes_recieved = max(votes_received_list)
  437.  
  438. if max_votes_recieved > 0:
  439. max_votes_candidate_index = votes_received_list.index(max_votes_recieved)
  440. winner_candidate = candidates[max_votes_candidate_index]
  441. context['winner_candidate'] = winner_candidate
  442.  
  443.  
  444. if context['object'] == get_constituency_election_eligible_to_vote(self.request.user):
  445. context['voting_link'] = '/elections/{}/{}/vote/security-step-1'.format(self.kwargs['election_id'], self.kwargs['pk'])
  446.  
  447. return context
  448.  
  449.  
  450. class ConstituencyElectionCandidateNominationView(FormView):
  451.  
  452. form_class = ConstituencyElectionCandidateNominationForm
  453. template_name = 'constituency_election_candidate_nomination_form_page.html'
  454.  
  455. def get_context_data(self, **kwargs):
  456. context = super(ConstituencyElectionCandidateNominationView, self).get_context_data(**kwargs)
  457.  
  458. # add constituency election object to context
  459. context['constituency_election_obj'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
  460.  
  461. return context
  462.  
  463. def form_valid(self, form):
  464. candidate_nomination = form.save(commit=False)
  465.  
  466. # set other required fields
  467. candidate_nomination.constituency_election_id = self.kwargs['pk']
  468. candidate_nomination.candidate = self.request.user
  469. candidate_nomination.save()
  470.  
  471. redirect_url = '/elections/{}/{}'.format(self.kwargs['election_id'], self.kwargs['pk'])
  472. return HttpResponseRedirect(redirect_url)
  473.  
  474.  
  475. class ConstituencyElectionCandidateNominationDeleteView(View):
  476.  
  477. def get(self, request, *args, **kwargs):
  478. ConstituencyElectionCandidateDetail.objects.filter(constituency_election_id=self.kwargs['pk'], candidate=self.request.user).delete()
  479. redirect_url = '/elections/{}/{}'.format(self.kwargs['election_id'], self.kwargs['pk'])
  480. return HttpResponseRedirect(redirect_url)
  481.  
  482.  
  483. class ConstituencyElectionCandidateDetailView(DetailView):
  484.  
  485. template_name = 'constituency_election_candidate_detail_page.html'
  486.  
  487. def get_queryset(self):
  488. return ConstituencyElectionCandidateDetail.objects.filter(constituency_election_id=self.kwargs['constituency_election_id'])
  489.  
  490.  
  491. ##Voting Views
  492.  
  493. class ConstituencyElectionVotingStep1(CheckValidVoterMixin, FormView):
  494.  
  495. form_class = ConstituencyElectionVotingStep1Form
  496. template_name = 'election_voting_step1.html'
  497.  
  498. def get_context_data(self, **kwargs):
  499. context = super(ConstituencyElectionVotingStep1, self).get_context_data(**kwargs)
  500.  
  501. # add constituency election object to context
  502. context['constituency_election_obj'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
  503.  
  504. return context
  505.  
  506. def get_form_kwargs(self):
  507. kwargs = super(ConstituencyElectionVotingStep1, self).get_form_kwargs()
  508. kwargs['user'] = self.request.user
  509. return kwargs
  510.  
  511. def send_email_otp(self):
  512. email_otp_object = ElectionEmailOTP.objects.filter(constituency_election_id=self.kwargs['pk'], user=self.request.user).first()
  513. if not email_otp_object:
  514. email_otp_object = ElectionEmailOTP.objects.create(constituency_election_id=self.kwargs['pk'], user=self.request.user)
  515.  
  516. if not email_otp_object.is_otp_valid():
  517. email_otp_object.otp_code = generate_otp_code()
  518. email_otp_object.created_on = timezone.now()
  519. email_otp_object.save()
  520.  
  521. 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)
  522. print otp_message
  523.  
  524. try:
  525. send_mail(subject='Email OTP for Voting', message=otp_message, from_email='pinky.1995gupta@gmail.com', recipient_list=[self.request.user.email])
  526. print "Email OTP sent successfully"
  527. except Exception as e:
  528. print repr(e) # print error message
  529.  
  530.  
  531. def form_valid(self, form):
  532. # set step-1 success flag
  533. self.request.session['{}_voting_step1_success'.format(self.request.user.id)] = True
  534.  
  535. # send email otp
  536. self.send_email_otp()
  537.  
  538. redirect_url = '/elections/{}/{}/vote/security-step-2'.format(self.kwargs['election_id'], self.kwargs['pk'])
  539. return HttpResponseRedirect(redirect_url)
  540.  
  541.  
  542. class ConstituencyElectionVotingStep2(CheckValidVoterMixin, CheckSecurityStep1SuccessMixin, FormView):
  543.  
  544. form_class = ConstituencyElectionVotingStep2Form
  545. template_name = 'election_voting_step2.html'
  546.  
  547. def get_context_data(self, **kwargs):
  548. context = super(ConstituencyElectionVotingStep2, self).get_context_data(**kwargs)
  549.  
  550. # add constituency election object to context
  551. context['constituency_election_obj'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
  552.  
  553. return context
  554.  
  555. def get_form_kwargs(self):
  556. kwargs = super(ConstituencyElectionVotingStep2, self).get_form_kwargs()
  557. kwargs['user'] = self.request.user
  558. kwargs['constituency_election'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
  559. return kwargs
  560.  
  561. def send_mobile_otp(self):
  562. mobile_otp_object = ElectionMobileOTP.objects.filter(constituency_election_id=self.kwargs['pk'], user=self.request.user).first()
  563. if not mobile_otp_object:
  564. mobile_otp_object = ElectionMobileOTP.objects.create(constituency_election_id=self.kwargs['pk'], user=self.request.user)
  565.  
  566. if not mobile_otp_object.is_otp_valid():
  567. mobile_otp_object.otp_code = generate_otp_code()
  568. mobile_otp_object.created_on = timezone.now()
  569. mobile_otp_object.save()
  570.  
  571. 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)
  572. print otp_message
  573.  
  574. try:
  575. send_sms(
  576. recipient_mobile_number = '+91'+self.request.user.mobile_number,
  577. message=otp_message
  578. )
  579. print "Mobile OTP sent successfully"
  580. except Exception as e:
  581. print repr(e) # print error message
  582.  
  583. def form_valid(self, form):
  584. # set step-2 success flag
  585. self.request.session['{}_voting_step2_success'.format(self.request.user.id)] = True
  586.  
  587. # send mobile otp
  588. self.send_mobile_otp()
  589.  
  590. redirect_url = '/elections/{}/{}/vote/security-step-3'.format(self.kwargs['election_id'], self.kwargs['pk'])
  591. return HttpResponseRedirect(redirect_url)
  592.  
  593.  
  594. class ConstituencyElectionVotingStep3(CheckValidVoterMixin, CheckSecurityStep1SuccessMixin, CheckSecurityStep2SuccessMixin, FormView):
  595.  
  596. form_class = ConstituencyElectionVotingStep3Form
  597. template_name = 'election_voting_step3.html'
  598.  
  599. def get_context_data(self, **kwargs):
  600. context = super(ConstituencyElectionVotingStep3, self).get_context_data(**kwargs)
  601.  
  602. # add constituency election object to context
  603. context['constituency_election_obj'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
  604.  
  605. return context
  606.  
  607. def get_form_kwargs(self):
  608. kwargs = super(ConstituencyElectionVotingStep3, self).get_form_kwargs()
  609. kwargs['user'] = self.request.user
  610. kwargs['constituency_election'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
  611. return kwargs
  612.  
  613. def form_valid(self, form):
  614. # set step-3 success flag
  615. self.request.session['{}_voting_step3_success'.format(self.request.user.id)] = True
  616.  
  617. redirect_url = '/elections/{}/{}/vote'.format(self.kwargs['election_id'], self.kwargs['pk'])
  618. return HttpResponseRedirect(redirect_url)
  619.  
  620.  
  621. class ConstituencyElectionVotingView(CheckValidVoterMixin, CheckSecurityStep1SuccessMixin, CheckSecurityStep2SuccessMixin, CheckSecurityStep3SuccessMixin, FormView):
  622.  
  623. form_class = ConstituencyElectionVotingForm
  624. template_name = 'election_voting_page.html'
  625.  
  626. def get_context_data(self, **kwargs):
  627. context = super(ConstituencyElectionVotingView, self).get_context_data(**kwargs)
  628.  
  629. # add constituency election object to context
  630. context['constituency_election_obj'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
  631. context['candidates'] = ConstituencyElectionCandidateDetail.objects.filter(constituency_election_id=self.kwargs['pk'], nomination_status=1)
  632.  
  633. return context
  634.  
  635. def get_form_kwargs(self):
  636. kwargs = super(ConstituencyElectionVotingView, self).get_form_kwargs()
  637. kwargs['user'] = self.request.user
  638. kwargs['constituency_election'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
  639. return kwargs
  640.  
  641. def form_valid(self, form):
  642. # save vote
  643. selected_candidate = ConstituencyElectionCandidateDetail.objects.filter(constituency_election_id=self.kwargs['pk'], nomination_status=1, id=form.cleaned_data['constituency_election_candidate']).first()
  644.  
  645. selected_candidate.votes_received += 1
  646. selected_candidate.save()
  647.  
  648. # save that user has voted in this election
  649. ElectionUserVoteDetail.objects.create(user=self.request.user, election=selected_candidate.constituency_election.election)
  650.  
  651. redirect_url = '/elections/{}/{}/vote/thanks'.format(self.kwargs['election_id'], self.kwargs['pk'])
  652. return HttpResponseRedirect(redirect_url)
  653.  
  654.  
  655. class ConstituencyElectionVotingSuccessView(TemplateView):
  656.  
  657. template_name = 'election_voting_success.html'
  658.  
  659. def get_context_data(self, **kwargs):
  660. context = super(ConstituencyElectionVotingSuccessView, self).get_context_data(**kwargs)
  661.  
  662. # add constituency election object to context
  663. context['constituency_election_obj'] = ConstituencyElectionDetail.objects.filter(election_id=self.kwargs['election_id'], pk=self.kwargs['pk']).first()
  664.  
  665. return context
Add Comment
Please, Sign In to add comment