F
FreemanT2Jan. 5, 2023, 11:35 a.m.

A voting site with Django

----------------------------Model----------------------------------------
class Voter(models.Model):
    gender_type = (('male', 'Male'), ('female', 'Female'))
    admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    gender = models.CharField(max_length=10, choices=gender_type)
    country_region = models.CharField(max_length=255, choices=Countries.choices, default=Countries.Pakistan)
    phone = PhoneNumberField(blank=True, unique=True)
    otp = models.CharField(max_length=10, null=True)
    verified = models.BooleanField(default=False)
    voted = models.BooleanField(default=False)
    otp_sent = models.IntegerField(default=0)  # Control how many OTPs are sent
    ip_address = models.GenericIPAddressField(unique=True, default='ABC')


    def __str__(self):
        return self.admin.first_name


class Position(models.Model):
    ACTIVE = 0
    INACTIVE = 1

    status_choice = ((ACTIVE, 'Active'), (INACTIVE, 'Inactive'))
    name = models.CharField(max_length=50, unique=True)
    max_vote = models.IntegerField()
    priority = models.IntegerField()
    description = models.TextField(null=True, blank=True)
    status = models.PositiveBigIntegerField(default=0, choices=status_choice)

    def __str__(self):
        return self.name


class Candidate(models.Model):
    fullname = models.CharField(max_length=50)
    photo = models.ImageField(upload_to="candidates")
    bio = models.TextField()
    position = models.ForeignKey(Position, on_delete=models.CASCADE, related_name='candidates')

    def __str__(self):
        return self.fullname

    def modify_points(self, added_points):
        self.points += added_points
        self.save()


class Votes(models.Model):
    voter = models.ForeignKey(Voter, on_delete=models.CASCADE)
    position = models.ForeignKey(Position, on_delete=models.CASCADE, related_name='positions')
    candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name='votes')


class BlockIP(models.Model):
    voter = models.ForeignKey(Voter, on_delete=models.CASCADE, related_name='ip')
    position = models.ForeignKey(Position, on_delete=models.CASCADE, related_name='positions_ip', null=True, blank=True)
    ip_address = models.GenericIPAddressField(default='abc')


@receiver(post_save, sender=Voter)
def default_to_non_active(sender, instance, created, **kwargs):
    if created:
        instance = BlockIP.objects.create(voter=instance, ip_address=instance.ip_address)
        instance.save()

-------------------------------------------- End of model-----------------------------------

def submit_ballot(request):
    if not request.user.is_authenticated:
        return redirect(reverse('index'))

    if request.method != 'POST':
        messages.error(request, "Please, browse the system properly")
        return redirect(reverse('index'))

    # Verify if the voter has voted or not
    voter = request.user.voter
    blocked = BlockIP.objects.filter(voter=voter)
    if voter.voted and blocked:
        messages.error(request, "You have voted already")
        return redirect(reverse('index'))

    form = dict(request.POST)
    form.pop('csrfmiddlewaretoken', None)  # Pop CSRF Token
    form.pop('submit_vote', None)  # Pop Submit Button

    # Ensure at least one vote is selected
    if len(form.keys()) < 1:
        messages.error(request, "Please select at least one candidate")
        return redirect(reverse('index'))
    positions = Position.objects.all()
    form_count = 0
    for position in positions:
        max_vote = position.max_vote
        pos = slugify(position.name)
        pos_id = position.id
        if position.max_vote > 1:
            this_key = pos + "[]"
            form_position = form.get(this_key)
            if form_position is None:
                continue
            if len(form_position) > max_vote:
                messages.error(request, "You can only choose " +
                               str(max_vote) + " candidates for " + position.name)
                return redirect(reverse('index'))
            else:
                for form_candidate_id in form_position:
                    form_count += 1
                    try:
                        candidate = Candidate.objects.get(id=form_candidate_id, position=position)
                        vote = Votes()
                        vote.candidate = candidate
                        vote.voter = voter
                        vote.position = position
                        vote.save()

                    except Exception as e:
                        messages.error(
                            request, "Please, browse the system properly " + str(e))
                        return redirect(reverse('index'))
        else:
            this_key = pos
            form_position = form.get(this_key)
            if form_position is None:
                continue
            # Max Vote == 1
            form_count += 1
            try:
                form_position = form_position[0]
                candidate = Candidate.objects.get(position=position, id=form_position)
                vote = Votes()
                vote.candidate = candidate
                vote.voter = voter
                vote.position = position
                vote.save()
            except Exception as e:
                messages.error(
                    request, "Please, browse the system properly " + str(e))
                return redirect(reverse('index'))

    # Count total number of records inserted
    # Check it viz-a-viz form_count
    inserted_votes = Votes.objects.filter(voter=voter)
    if (inserted_votes.count() != form_count):
        # Delete
        inserted_votes.delete()
        messages.error(request, "Please try voting again!")
        return redirect(reverse('index'))
    else:
        # Update Voter profile to voted
        voter.voted = True
        voter.save()
        messages.success(request, "Thanks for voting")
        return redirect(reverse('index'))

When a poll is create, and a candidate is added to that poll, a voter can vote any candidate, my problem now is if a voter already voted, that voter cannot vote again even when another poll is created, what i want is a voter can still vote in another poll regardless of voting on a poll already

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

0

Comments

Only authorized users can post comments.
Please, Log in or Sign up
L
  • Leo
  • Sept. 26, 2023, 6:43 p.m.

C++ - Test 002. Constants

  • Result:41points,
  • Rating points-8
L
  • Leo
  • Sept. 26, 2023, 6:32 p.m.

C++ - Test 001. The first program and data types

  • Result:93points,
  • Rating points8
Last comments
IscanderChe
IscanderCheSept. 13, 2023, 4:11 p.m.
QScintilla C++ example По горячим следам (с другого форума вопрос задали, пришлось в памяти освежить всё) решил дополнить. Качаем исходники с https://riverbankcomputing.com/software/qscintilla/downlo…
Evgenii Legotckoi
Evgenii LegotckoiSept. 6, 2023, 2:18 p.m.
Qt/C++ - Lesson 048. QThread — How to work with threads using moveToThread Разве могут взаимодействовать объекты из разных нитей как-то, кроме как через сигнал-слоты?" Могут. Выполняя оператор new , Вы выделяете под объект память в куче (heap), …
AC
Andrei CherniaevSept. 5, 2023, 10:37 a.m.
Qt/C++ - Lesson 048. QThread — How to work with threads using moveToThread Я поясню свой вопрос. Выше я писал "Почему же в методе MainWindow::on_write_1_clicked() Можно обращаться к методам exampleObject_1? Разве могут взаимодействовать объекты из разных…
n
nvnAug. 31, 2023, 4:47 p.m.
QML - Lesson 004. Signals and Slots in Qt QML Здравствуйте! Прекрасный сайт, отличные статьи. Не хватает только готовых проектов для скачивания. Многих комментариев типа appCore != AppCore просто бы не было )))
NSProject
NSProjectAug. 24, 2023, 8:40 p.m.
Django - Tutorial 023. Like Dislike system using GenericForeignKey Ваша ошибка связана с gettext from django.utils.translation import gettext_lazy as _ Поле должно выглядеть так vote = models.SmallIntegerField(verbose_name=_("Голос"), choices=VOTES) …
Now discuss on the forum
IscanderChe
IscanderCheSept. 17, 2023, 4:24 p.m.
Интернационализация строк в QMessageBox Странная картина... Сделал минимально работающий пример - всё работает. Попробую на другой операционке. Может, дело в этом.
NSProject
NSProjectSept. 17, 2023, 3:49 p.m.
Помогите добавить Ajax в проект В принципе ничего сложного с отправкой на сервер нет. Всё что ты хочешь отобразить на странице передаётся в шаблон и рендерится. Ты просто создаёшь файл forms.py в нём описываешь свою форму и в …
BlinCT
BlinCTSept. 15, 2023, 7:35 p.m.
Размеры полей в TreeView Всем привет. Пытаюсь сделать дерево вот такого вида Пытаюсь организовать делегат для каждой строки в дереве. ТО есть отступ какого то размера и если при открытии есть под…
IscanderChe
IscanderCheSept. 8, 2023, 7:07 p.m.
Кастомная QAbstractListModel и цвет фона, цвет текста и шрифт Похоже надо не абстрактный , а "реальный" типа QSqlTableModel Да, но не совсем. Решилось с помощью стайлшитов и setFont. Спасибо за отлик!
Evgenii Legotckoi
Evgenii LegotckoiSept. 6, 2023, 1:35 p.m.
Вопрос: Нужно ли в деструкторе удалять динамически созданные QT-объекты. Напр: Зависит от того, как эти объекты были созданы. Если вы передаёте указатель на parent объект, то не нужно, Ядро Qt само разрулит удаление, если нет, то нужно удалять вручную, иначе будет ут…

Follow us in social networks