Home>
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
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= 'User',
on_delete= models.PROTECT)
-
Answer # 1
Related questions
- python : Data not being pushed into database from Django form
- python : Database image not showing in Django project
- python : Django. Using ldap authorization and user groups in different AD domains
- python : mapping to a specific user group in Django 4
- python : cannot import name 'url' from 'django.conf.urls' when working with Django 4.0.1
- python : Try using "django.db.backends.XXX" where XXX is one of:
- python : unable to establish connection between my django project and mongodb database (deployed locally)
- Python and Django version compatibility for an existing project
- python : Pull data from different tables django
- python : Django and ForeignKey
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 object
Choose
cpk= 1
, but himvoter
when the function is called is different, so Django tries to create an object withpk= 1
andvoter= reqeust.user
... But sincepk
is 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 argument
pk
...thank you it helped.
tammalako2021-12-29 05:21:55