D
D
Domohod2021-12-28 20:27:04
Python
Domohod, 2021-12-28 20:27:04

Why does IntegrityError at / UNIQUE constraint failed: registration_choose.id occur?

I'm making a website in django. I am doing a vote and I want the user who voted to get into the database, for which I write voter.request.user. But because of that, this error occurs. How can I fix it?

django.db.utils.IntegrityError: UNIQUE constraint failed: registration_choose.id
[28/Dec/2021 20:11:17] "GET / HTTP/1.1" 500 17808


views.py:

def home(request):
    value, created = Choose.objects.get_or_create(voter=request.user, pk=1)
    context = {
        "value": value,
    }

return render(request, 'registration/home.html', context)



def black(request):
    value, created = Choose.objects.get_or_create(voter=request.user, pk=1)

    if request.method == 'POST':
        select_action = request.POST['choose']

        if select_action == 'black':
            value.count_black += 1
            value.save()
        else:
            return render(request, 'registration/black.html', {"value": value})

        return redirect("home")


    context = {"value": value}
    return render(request, 'registration/black.html', context)


models.py:

from django.contrib.auth.models import User
from django.db import models


class Choose(models.Model):
    count_black = models.PositiveIntegerField(default=0, verbose_name="black")
    count_white = models.PositiveIntegerField(default=0, verbose_name="white")
    count_purple = models.PositiveIntegerField(default=0, verbose_name="purple")
    voter = models.ForeignKey(User, null=True, verbose_name='Пользователь', 
    on_delete=models.PROTECT)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-12-28
@Domohod

pk=1get_or_createredundant in the method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question