Example #1
0
def submit_vote(request, question_id):
    """
	Submits a vote that has been made in the show_question view
	"""

    question = get_object_or_404(PollQuestion, poll=user.poll, id=question_id)

    next_question = question.next()
    valid_choices = {"yes": 0, "no": 1, "abstention": 2}

    # Check if the vote key exists and contains a valid value. Otherwise,
    # redirect to next question
    if not "vote" in request.POST or not request.POST["vote"] in valid_choices:
        if next_question == None:
            return HttpResponseRedirect(reverse("thanks"))

        return HttpResponseRedirect(reverse("show_question", kwargs={"question_id": next_question.id}))

        # Check if user already voted on this. If not, create new Vote object
    try:
        vote = Vote.objects.get(voting_user=user, poll_question=question)
    except Vote.DoesNotExist:
        vote = Vote(voting_user=user, poll_question=question)

    vote.choice = valid_choices[request.POST["vote"]]
    vote.save()

    if next_question == None:
        return HttpResponseRedirect(reverse("thanks"))

    return HttpResponseRedirect(reverse("show_question", kwargs={"question_id": next_question.id}))
Example #2
0
def create_vote(request, id):
    ''' Add a new vote to the system. '''

    # TODO:
    # - only allow a user to vote once on each ticket
    # - include the time that the vote was registered
    # - display a confirmation message in the template using the django messaging system

    ticket = get_object_or_404(Ticket, id=id)
    vote = Vote(ticket=ticket, user=request.user)

    if ticket.type == 'feature':
        vote.completed = True
        vote.save()
        #  Confirm Success message ######
        messages.success(request,
                         "Your Vote has been added to the Payment Feature!")

        return redirect('payment_form', id)

    else:
        # is a bug
        vote.completed = True
        vote.save()

        # Add confirmation message
        messages.success(request, "Your Vote has been added to the bug!")

    return redirect('ticket_detail', id)
Example #3
0
def woman(request):
    v = Vote(type=True)
    v.survey = Survey.get()
    v.save()
    votes = Vote.objects.filter(survey=v.survey).order_by('-date')
    mtot = votes.filter(type=Man).count()
    wtot = votes.filter(type=Woman).count()
    return redirect('/vote/')
Example #4
0
def add_car_vote(request, car_name):
    s = Survey.get()
    v = Vote()
    v.survey = s
    v.choice = car_name
    v.save()
    cnt = Vote.objects.filter(survey=s, choice=car_name).count()
    return HttpResponse(str(cnt))
Example #5
0
def VoteQuestion(request, questionid):
    option = request.POST.get(questionid)
    option_obj = Question_option.objects.get(pk=option)
    question_obj = Question.objects.get(pk=questionid)
    username = request.user.username
    applyVote = Vote(question=question_obj, username=username, question_option=option_obj)
    applyVote.save()
    request.session['message'] = 'Your poll has been accepted'
    return redirect('/questions/'+str(questionid))
Example #6
0
def add_vote(article, user, vote_value):
    vote = Vote()
    apply_article_rating(article, vote_value)
    vote.voteUrl = article
    vote.voter = user
    vote.voteValue = vote_value
    vote.save()
    json_data = vote.as_json()
    return json_data
Example #7
0
def VoteQuestion(request, questionid):
    option = request.POST.get(questionid)
    option_obj = Question_option.objects.get(pk=option)
    question_obj = Question.objects.get(pk=questionid)
    username = request.user.username
    applyVote = Vote(question=question_obj,
                     username=username,
                     question_option=option_obj)
    applyVote.save()
    request.session['message'] = 'Your poll has been accepted'
    return redirect('/questions/' + str(questionid))
Example #8
0
def vote(request):
    if request.method == "POST":
        vote = Vote()
        vote.img_a = Image.objects.get(pk=request.POST["img_a"])
        vote.img_b = Image.objects.get(pk=request.POST["img_b"])
        vote.user = request.user
        vote.winner = Image.objects.get(pk=request.POST["winner"])
        vote.save()

    img_a, img_b = contenders(request.user)

    return render(request, 'vote/vote.html', {"img_a": img_a, "img_b": img_b})
Example #9
0
 def test_has_user_voted_for_song(self):
     vote_service = VoteService()
     vote = Vote()
     vote.user_id = 1
     vote.song_id = 1
     vote.created_date = datetime.now()
     vote.like = True
     vote.save()
     user = User()
     user.id = 1
     song = Song
     song.id = 1
     self.assertTrue(vote_service.has_user_voted_for_song(song, user))
Example #10
0
def vote(request, question_id, wechat_id=None):
    if request.method == "GET":
        question = get_object_or_404(Question, pk=question_id)
        choices = Choice.objects.filter(question=question)
        gt = geetest.geetest(settings.CAPTCHA_ID, settings.PRIVATE_KEY)
        challenge = gt.geetest_register()
        BASE_URL = "api.geetest.com/get.php?gt="
        if len(challenge) == 32:
            geetest_url = "http://%s%s&challenge=%s&product=embed" % (BASE_URL, settings.CAPTCHA_ID, challenge)
        context = {
            "question": question,
            "choices": choices,
            "geetest_url": geetest_url,
        }
        return render(request, "vote/vote-page.html", context=context)

    if request.method == "POST":
        challenge = request.POST.get('geetest_challenge', '')
        validate = request.POST.get('geetest_validate', '')
        seccode = request.POST.get('geetest_seccode', '')
        gt = geetest.geetest(settings.CAPTCHA_ID, settings.PRIVATE_KEY)
        result = gt.geetest_validate(challenge, validate, seccode)
        if not result:
            messages.warning(request, '验证失败')
            return redirect(reverse('vote-page', args=(question_id,)))
        if wechat_id == None:
            try:
                user = VoteUser.objects.get(username=request.session["vote_user"])
            except:
                messages.warning(request, '请先登录投票系统或发送"投票"到微信公众号"创新人才"获取投票链接')
                return redirect(reverse('vote-page', args=(question_id,)))
        else:
            try:
                user = VoteUser.objects.get(openid=wechat_id)
            except:
                messages.warning(request, '用户ID无效,请发送"投票"到微信公众号"创新人才"获取相关信息')
                return redirect(reverse('vote-page', args=(question_id,)))
        question = get_object_or_404(Question, pk=question_id)
        polls = request.POST.getlist("check_box_list")
        if len(polls) > question.max_choice:
            polls = polls[:question.max_choice]
        for poll in polls:
            poll_obj = get_object_or_404(Choice, id=int(poll))
            vote = Vote(choice=poll_obj, user=user)
            vote.save()
        messages.success(request, "投票成功~谢谢您的参与~")
        return redirect(reverse('vote_page', args=(question_id,)))
Example #11
0
def voteProposition(request):
    resp = {}
    user = VoteUser.objects.filter(userkey=request.GET.get('userkey'))[0]
    if (user is None):
        resp['code'] = 'authentication error'
        return HttpResponse(json.dumps(resp), content_type='application/json')

    proposition = VoteProposition.objects.filter(
        id=request.GET.get('propositionid'))[0]
    votes = Vote.objects.filter(user=user, proposition=proposition)
    if (votes.count() == 0):
        v = Vote()
    else:
        v = votes[0]
        if (v.voteType == 1):
            proposition.strongDisagreeNb -= 1
        if (v.voteType == 2):
            proposition.disagreeNb -= 1
        if (v.voteType == 3):
            proposition.agreeNb -= 1
        if (v.voteType == 4):
            proposition.strongAgreeNb -= 1

    v.proposition = proposition
    v.user = user
    #1-pro, 2-against
    v.voteType = int(request.GET.get('type'))
    if (v.voteType == 1):
        proposition.strongDisagreeNb += 1
    if (v.voteType == 2):
        proposition.disagreeNb += 1
    if (v.voteType == 3):
        proposition.agreeNb += 1
    if (v.voteType == 4):
        proposition.strongAgreeNb += 1
    proposition.save()
    v.save()
    resp['id'] = v.id
    resp['strongDisagreeNb'] = proposition.strongDisagreeNb
    resp['disagreeNb'] = proposition.disagreeNb
    resp['agreeNb'] = proposition.agreeNb
    resp['strongAgreeNb'] = proposition.strongAgreeNb
    return HttpResponse(json.dumps(resp), content_type='application/json')
Example #12
0
def index(request):
    s = Survey.get()
    current_vote = request.GET.get('type')
    current_car = request.GET.get('car')
    if current_vote in ('man', 'woman'):
        if current_vote == 'man':
            v = Vote(type=Man)
        else:
            v = Vote(type=Woman)
        v.survey = s
        v.save()
    elif current_car:
        if current_car != 'delete':
            v = Vote()
            v.survey = s
            v.choice = current_car
            v.save()
        else:
            vote = Vote.objects.last()
            vote.delete()

    votes = Vote.objects.filter(survey=s).order_by('-date')
    if s == 'tesla':
        cnt = votes.count()
        #tallies = Vote.objects.filter(survey=s).values('choice').annotate(Count('choice')).order_by('choice')
        tallies = {}
        tallies['TeslaS'] = Vote.objects.filter(survey=s, choice='tesla_s').count()
        tallies['TeslaX'] = Vote.objects.filter(survey=s, choice='tesla_x').count()
        tallies['Tesla3'] = Vote.objects.filter(survey=s, choice='tesla_3').count()


        return render(request, 'vote/cars.html', {'vtot': cnt,
                                                  'tallies': tallies,
                                                  'survey': s,
                                                  'votes': votes[0:5]})
    else:
        mtot = votes.filter(type=Man).count()
        wtot = votes.filter(type=Woman).count()
        return render(request, 'vote/index.html', {'vtot': mtot+wtot,
                                                   'mtot': mtot,
                                                   'wtot': wtot,
                                                   'survey': s,
                                                   'votes': votes[0:5]})
    def test_category(self):
        # Check that <category> value which is not
        # listed in VoteCategory enum
        # does not confuse Django ORM

        vote = Vote(congress=2011, session='2011',
                    chamber=CongressChamber.senate,
                    number=10,
                    source=VoteSource.random_value(),
                    created=datetime.now(),
                    vote_type='asdf',
                    category='zzz',
                    question='asdf',
                    required='asdf',
                    result='asdf')
        vote.save()

        self.assertEqual(vote.category, u'zzz')
        self.assertEqual(vote.get_category_display(), u'zzz')
Example #14
0
def create_votes():

	Vote.objects.all().delete()

	for pk, fields in votos.iteritems():

		try:
			v = Vote(pk=pk)
			v.user_id = get_user(fields['user'])
			v.value = fields['value']
			v.content_object = Dateo.objects.get(pk=fields['object_id'])
			v.object_id = fields['object_id']
			v.client_domain = datea
			v.save()

			created = date_parser(fields['created'])
			Vote.objects.filter(pk=v.pk).update(created=created)

		except: 
			pass
Example #15
0
def cast(request, poll_id, candidate_id):

    #Acquire data about the logged in user
    username = request.user.username
    student = Student.objects.get(user=request.user)

    #Assure that student is able to vote in the selected poll and has not already voted.
    #Also assure that the selected candidate is contesting for the selected poll
    try:
        poll = Poll.objects.get(
            id=poll_id)  #Extract poll data. Generate Exception if not found
        assert poll.active  #ensure that the poll is running
        assert poll.category == "HR" or poll.grade == student.grade  #Ensure that student is allowed to vote
        assert student not in poll.voted.all(
        )  #Ensure that the student has not already voted
        assert Candidate.objects.get(id=candidate_id) in poll.candidates.all(
        )  #Verify selected candidate_id
    except:
        return HttpResponseRedirect("/index/")  #Go back to polls page

    #Mark the logged in student as voted in the selected poll
    poll.voted.add(student)
    poll.save()

    #Get the selected candidate's data and current time
    candidate = Candidate.objects.get(id=candidate_id)
    poll_date = time.strftime("%Y-%m:%D")
    poll_time = time.strftime("%H:%M:%S")

    #Add a vote for the selected candidate in the Vote table
    vote_to_cast = Vote(poll=poll,
                        candidate=candidate,
                        poll_date=poll_date,
                        poll_time=poll_time)
    vote_to_cast.save()

    return HttpResponseRedirect(
        "/index/?vote_casted=True")  #Redirect to polls page
Example #16
0
from django.core.mail import send_mail
from intranet.models import Member, Group
from vote.models import Vote
from django.utils.crypto import get_random_string

members = Member.objects.all()

poll = int(raw_input("Poll id: "))

for m in members:
    key = get_random_string(
        length=32,
        allowed_chars=
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
    v = Vote(user=m, key=key, poll=poll)
    v.save()
    email = """Dear %s,

We've been working on updating the ACM constitution to better reflect how we currently operate and to incorporate some new ideas. Under the guidelines of the current constitution, amendments have to be approved by our executive council and then by our membership. The proposed changes have been approved by exec, so now we're sending it out to you so that you can take a look at it and vote on it. 

Here's a link to the new constitution https://www-s.acm.illinois.edu/confluence/display/general/ACM+Constitution+-+Draft; there's also a summary of the changes below. 

Amendment highlights:
-Classifying members as undergraduate members, graduate members, faculty/staff members, active members and alumni members
-Updating duties of officers
-Not allowing officers to run for a second consecutive term in the same position 
-Making it possible for individuals to get funding for a project in addition to SIGs
-Defining what committees are and how they're run
-Requiring 5 members to start a SIG
-Allowing for a designated proxy for SIG leadership at exec meetings 
-Defining the requirements of an active SIG and what happens when they're no longer active 
Example #17
0
def election(request, elecName):
    votearea = DummyCitizenInfo.objects.get(email=request.user.email)
    electionobj = Election.objects.get(elec_name=elecName)
    admincandidates = CanInfo.objects.filter(elec_name=elecName)
    if (electionobj.elec_type == 'national'):
        candidates = CanInfo.objects.filter(elec_name=elecName,
                                            voting_area=votearea.area_name)
    else:
        # mayorcandidates=CanInfo.objects.filter(elec_name = elecName, candidate_type = 'MAYOR')
        candidates = CanInfo.objects.filter(
            Q(elec_name=elecName) & Q(voting_ward=votearea.ward_number)
            | Q(voting_ward='M'))
    print(admincandidates)

    canlistname = []
    canlistphoto = []
    candiparty = []
    canlisttype = []
    canlistnid = []
    counter = []
    canlistward = []
    canlistarea = []

    admincanlistname = []
    admincanlistphoto = []
    admincandiparty = []
    admincanlisttype = []
    admincanlistnid = []
    admincounter = []
    admincanlistward = []
    admincanlistarea = []
    for j in range(len(admincandidates)):
        dummyvar = DummyCitizenInfo.objects.get(nid=admincandidates[j].nid)
        admincanlistname.append(dummyvar.name)
        admincanlistphoto.append(dummyvar.picture)
        admincanlisttype.append(admincandidates[j].candidate_type)
        admincandiparty.append(admincandidates[j].party_name)
        admincanlistnid.append(admincandidates[j].nid)
        admincanlistward.append(admincandidates[j].voting_ward)
        admincanlistarea.append(admincandidates[j].voting_area)
        admincounter.append(
            Vote.objects.filter(elec_name=elecName,
                                candidate=admincandidates[j]).count())

    for i in range(len(candidates)):
        dummyvar = DummyCitizenInfo.objects.get(nid=candidates[i].nid)
        canlistname.append(dummyvar.name)
        canlistphoto.append(dummyvar.picture)
        canlisttype.append(candidates[i].candidate_type)
        candiparty.append(candidates[i].party_name)
        canlistnid.append(candidates[i].nid)
        canlistward.append(candidates[i].voting_ward)
        canlistarea.append(candidates[i].voting_area)
        counter.append(
            Vote.objects.filter(elec_name=elecName,
                                candidate=candidates[i]).count())
    print(canlistname)
    flag = Vote.objects.filter(
        elec_name=elecName,
        user=DummyCitizenInfo.objects.get(email=request.user.email),
        vote_status=True)
    context = {
        'uData':
        DummyCitizenInfo.objects.get(email=request.user.email),
        'getElectionData':
        CanInfo.objects.filter(elec_name=elecName),
        'electionTable':
        Election.objects.get(elec_name=elecName),
        'elec_name':
        elecName,
        'admincanlistcity':
        zip(admincanlistname, admincanlisttype, admincanlistward,
            admincounter),
        'admincanlistnational':
        zip(admincanlistname, admincandiparty, admincanlistarea, admincounter),
        'canlist':
        zip(canlistname, canlistphoto, canlisttype, candiparty, canlistnid),
        'canlist1':
        zip(canlistname, canlistphoto, canlisttype, candiparty, canlistnid),
        'canlist2':
        zip(canlistname, canlistphoto, canlisttype, candiparty, canlistnid),
        'canlist3':
        zip(canlistname, canlisttype, canlistward, counter),
        'nationalcanlist':
        zip(canlistname, candiparty, canlistarea, counter),
        'voteFlag':
        flag,
        'votearea':
        votearea
    }
    if request.method == 'POST':
        et = Election.objects.get(elec_name=elecName)
        if request.POST.get('actionOp') == 'active':
            et.elec_status = request.POST.get('actionOp')
            et.save()
        if request.POST.get('actionOp') == 'cancle':
            Election.objects.get(elec_name=elecName).delete()
            CanInfo.objects.filter(elec_name=elecName).delete()
        if request.POST.get('actionOp') == 'ended':
            et.elec_status = 'ended'
            et.save()
        if request.POST.get('MAYOR') and request.POST.get(
                'COUNCILLOR') and request.POST.get('RESERVED'):
            vModel1 = Vote(
                elec_name=elecName,
                vote_status=True,
                user=DummyCitizenInfo.objects.get(email=request.user.email),
                candidate=CanInfo.objects.filter(candidate_type='MAYOR').get(
                    nid=request.POST.get('MAYOR')))
            vModel2 = Vote(
                elec_name=elecName,
                vote_status=True,
                user=DummyCitizenInfo.objects.get(email=request.user.email),
                candidate=CanInfo.objects.filter(
                    candidate_type='COUNCILLOR').get(
                        nid=request.POST.get('COUNCILLOR')))
            vModel3 = Vote(
                elec_name=elecName,
                vote_status=True,
                user=DummyCitizenInfo.objects.get(email=request.user.email),
                candidate=CanInfo.objects.filter(
                    candidate_type='RESERVED').get(
                        nid=request.POST.get('RESERVED')))
            vModel1.save()
            vModel2.save()
            vModel3.save()
        if request.POST.get('MP'):
            vModel1 = Vote(
                elec_name=elecName,
                vote_status=True,
                user=DummyCitizenInfo.objects.get(email=request.user.email),
                candidate=CanInfo.objects.filter(
                    candidate_type='MP',
                    elec_name=elecName).get(nid=request.POST.get('MP')))
            vModel1.save()

        checkAccess = DummyCitizenInfo.objects.get(email=request.user.email)
        if checkAccess.elec_Worker == True:
            return redirect('election-worker')
        else:
            return redirect('dashboard')
    elif Election.objects.filter(elec_name=elecName, elec_type='national'):
        return render(request, 'home/national.html', context)
    elif Election.objects.filter(elec_name=elecName, elec_type='city'):
        return render(request, 'home/city.html', context)
Example #18
0

from django.core.mail import send_mail
from intranet.models import Member, Group
from vote.models import Vote
from django.utils.crypto import get_random_string


members = Member.objects.all()

poll=int(raw_input("Poll id: "))

for m in members:
   key = get_random_string(length=32,allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
   v = Vote(user=m,key=key,poll=poll)
   v.save()
   email = """Dear %s,

We've been working on updating the ACM constitution to better reflect how we currently operate and to incorporate some new ideas. Under the guidelines of the current constitution, amendments have to be approved by our executive council and then by our membership. The proposed changes have been approved by exec, so now we're sending it out to you so that you can take a look at it and vote on it. 

Here's a link to the new constitution https://www-s.acm.illinois.edu/confluence/display/general/ACM+Constitution+-+Draft; there's also a summary of the changes below. 

Amendment highlights:
-Classifying members as undergraduate members, graduate members, faculty/staff members, active members and alumni members
-Updating duties of officers
-Not allowing officers to run for a second consecutive term in the same position 
-Making it possible for individuals to get funding for a project in addition to SIGs
-Defining what committees are and how they're run
-Requiring 5 members to start a SIG
-Allowing for a designated proxy for SIG leadership at exec meetings 
-Defining the requirements of an active SIG and what happens when they're no longer active 
Example #19
0
    def post(self, request):
        voter = request.user.voter

        # Check if the voter has already voted
        # If not yet...
        if not voter.voting_status:
            # Take note of the voter's votes
            votes = []
            poll_votes = []

            # Collect all "voteable" positions
            positions = request.POST.getlist('position')

            # Collect all polls
            polls = request.POST.getlist('poll')

            if positions is not False and len(positions) > 0:
                for position in positions:
                    # For each position, get the voter's pick through its identifier
                    # It should return False when the voter abstained for that position (picked no one)
                    votes.append((
                        position,
                        request.POST.get(position, False),
                    ))

            if polls is not False and len(polls) > 0:
                for poll in polls:
                    poll_votes.append((
                        poll,
                        request.POST.get(poll)
                        [request.POST.get(poll).rfind('-') + 1:],
                    ))

            # Proceed only when there are no duplicate votes and positions
            if self.contains_duplicates(votes) and self.contains_duplicates(
                    poll_votes):
                # If there are no duplicates, convert the list of tuples into a dict
                votes_dict = {}

                for vote in votes:
                    votes_dict[vote[0]] = vote[1]

                votes = votes_dict

                poll_votes_dict = {}

                for poll in poll_votes:
                    poll_votes_dict[poll[0]] = poll[1]

                polls = poll_votes_dict

                try:
                    # Change the identifiers to the actual candidates they represent
                    for position, candidate in votes.items():
                        votes[position] = (
                            Position.objects.get(identifier=position),
                            Candidate.objects.get(identifier=candidate)
                            if candidate is not False else False,
                        )

                    for identifier, answer in polls.items():
                        polls[identifier] = (
                            Poll.objects.get(identifier=identifier),
                            answer,
                        )

                    with transaction.atomic():
                        # Create a vote object to represent a single vote of a user
                        vote = Vote(voter_id_number=voter.user.username,
                                    voter_college=voter.college.name)
                        vote.save()

                        # Generate its serial number
                        serial_number = self.generate_serial_number(vote.id)

                        vote.serial_number = serial_number
                        vote.save()

                        # Create a vote set array representing the individual votes to be saved in the database
                        actual_votes = [
                            VoteSet(vote=vote,
                                    candidate=(position_candidate[1]
                                               if position_candidate[1]
                                               is not False else None),
                                    position=position_candidate[0])
                            for position_candidate in votes.values()
                        ]

                        actual_poll_votes = [
                            PollSet(vote=vote,
                                    poll=(poll[0]),
                                    answer=(poll[1]))
                            for poll in polls.values()
                        ]

                        # Save all votes into the database
                        for actual_vote in actual_votes:
                            actual_vote.save()

                        for actual_poll_vote in actual_poll_votes:
                            actual_poll_vote.save()

                        # Send email receipt
                        self.send_email_receipt(request.user, votes,
                                                serial_number)

                        # Mark the voter as already voted
                        voter.voting_status = True
                        voter.save()

                    # Log the user out
                    logout(request)

                    return redirect('logout:logout_voter')
                except PollAnswerType.ValueError:
                    # One of the votes for the polls is not a valid answer
                    messages.error(
                        request,
                        'Some of your answers to the polls do not exist')

                    return self.get(request)
                except Candidate.DoesNotExist:
                    # One of the votes do not represent a candidate
                    messages.error(
                        request, 'One of your voted candidates do not exist.')

                    return self.get(request)
                except IntegrityError:
                    # A vote has already been created to the voter's name, meaning he has already voted
                    messages.error(request,
                                   'You may have already voted before.')

                    # Log the user out
                    logout(request)

                    voter.voting_status = True
                    voter.save()

                    return redirect('logout:logout_fail')
                # except SMTPException:
                #     # Could not send an email receipt
                #     messages.error(request, 'Could not send an email receipt to your email address.')
                #
                #     return self.get(request)
            else:
                # If there are duplicate votes
                messages.error(
                    request, 'There are duplicate votes in your submission.')

                return self.get(request)
        else:
            # But if the voter already did...
            messages.error(request,
                           'You have already voted. You may only vote once.')

            # Log the user out
            logout(request)

            return redirect('logout:logout_fail')
Example #20
0
    def post(self, request):
        message_fr = "Merci pour votre vote Bonne chance pour la tombola RDV le 18 février 2021 sur 2M"
        message_ar = "شكرا لتصويتكم حظ موفق موعدنا يوم 18 فبراير 2021 على قناة 2M  "
        status = "success"

        data = request.data

        temp_person = Person.objects.all().filter(email=data["email"])


        config_demo = Config.objects.all().filter(type="demo", active=True)
        site_demo = False
        if config_demo.count() == 1:
            site_demo = True

        if temp_person.count() > 0: # and site_demo == False
            message_fr = "Vote non enregistré. Vous avez déjà voté pour votre candidat préféré."
            message_ar = "لم يتم تسجيل التصويت. لقد قمتم بالفعل بالتصويت لمرشحكم المفضل. "
            return Response({"status": "error", "message_fr": message_fr, "message_ar": message_ar, "uid_ref": "",
                             "site_demo": site_demo}, content_type="application/json", status=200)

        uid_ref = None
        candidat = Candidat.objects.all().filter(uid=data["candidat"])
        config_vote = Config.objects.all().filter(type="vote", active=True)
        if candidat.count() == 1 and config_vote.count() > 0:
            candidat = candidat[0]




            uid_ref = self.generateUID() + "-" + self.generateUID()
            person = Person()
            person.name = data["name"]
            person.email = data["email"]
            person.phone = str(data["phone"])
            person.uid = self.generateUID()
            person.uid_ref = uid_ref
            person.accept_reglement = True

            person.save()

            vote = Vote()
            vote.candidat = candidat
            vote.person = person
            vote.uid = self.generateUID()
            vote.project = candidat.project

            vote.save()

            candidat.total_votes = candidat.total_votes + 1
            candidat.save()
        else:
            if config_vote.count() == 0 :
                status = "error"
                message_fr = "Le vote est fermé, Merci pour votre visite."
                message_ar = "لقد تم إغلاق التصويت، شكرا لزيارتكم."
            else:
                status = "error"
                message_fr = "Candidat n'existe plus, Merci de réessayer plus tard"
                message_ar = "لم يعد المرشح موجودًا ، يرجى المحاولة مرة أخرى لاحقًا"


        return Response({ "status" : status, "message_fr" : message_fr, "message_ar" : message_ar, "uid_ref" : uid_ref, "site_demo" : site_demo}, content_type="application/json", status=200)