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
Рекомендуємо хостинг TIMEWEB
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.Magst du es? In sozialen Netzwerken teilen!
Kommentare
sf
- sdfsdfkp fgskpgokspdog
- 14. Oktober 2024 15:09
C++ - Тест 004. Указатели, Массивы и Циклы
- Ergebnis:90punkte,
- Bewertungspunkte8
МВ
- Максим Васильев
- 2. Oktober 2024 04:14
Qt - Тест 001. Сигналы и слоты
- Ergebnis:68punkte,
- Bewertungspunkte-1
ЛС
- Лев Семенов
- 30. September 2024 11:04
C++ - Тест 001. Первая программа и типы данных
- Ergebnis:53punkte,
- Bewertungspunkte-4
Letzte Kommentare
ИМ
Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
Игорь Максимов5. Oktober 2024 07:51
QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
АК
Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
Анатолий Кононенко5. Februar 2024 01:50
EVA25. Dezember 2023 10:30
Jetzt im Forum diskutieren
добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
ИМ
Реализация навигации по разделам Спасибо Евгений!
Игорь Максимов3. Oktober 2024 04:05
Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
КГ
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
Кирилл Гусарев27. September 2024 09:09
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …