I am making a site in django. I make a vote and I want the voted user to get into the database, for which I am writingvoter.request.user... But because of this, 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 178087


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 ()
            return render (request, 'registration /black.html', {"value": value})
        return redirect ("home")
    context= {"value": value}
    return render (request, 'registration /black.html', context)


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= 'User',
    on_delete= models.PROTECT)
  • Answer # 1

    Method.get_or_create ()returns an object if it matches the search criteria. Otherwise, it creates a new object with the arguments passed to it.

    Apparently, your database already has one objectChoosecpk= 1, but himvoterwhen the function is called is different, so Django tries to create an object withpk= 1andvoter= reqeust.user... But sincepkis a unique field, which means that there cannot be two objects with onepk, he throws such an error.

    In my opinion, to fix this error, it is enough to remove the argumentpk...

    thank you it helped.

    tammalako2021-12-29 05:21:55