VITALYS WEB VITALYS WEB - 2 months ago 15
Python Question

django.db.utils.IntegrityError: UNIQUE constraint failed: core_profile.user_id

I'm starting my first webproject with django,

-I have created an APP "core" to handle registration and login

-During the registration i want the user to submit some additional informations
to create a Userprofile

-I extended Django's default User model with

OneToOne
relation

i'm gettin this error when i try to upload files

Traceback:

File "C:\Python36\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)

File "C:\Python36\lib\site-packages\django\db\backends\sqlite3\base.py" in
execute
328. return Database.Cursor.execute(self, query, params)

The above exception (UNIQUE constraint failed: core_profile.user_id) was the
direct cause of the following exception:

File "C:\Python36\lib\site-packages\django\core\handlers\exception.py" in
inner
41. response = get_response(request)

File "C:\Python36\lib\site-packages\django\core\handlers\base.py" in
_get_response
187. response = self.process_exception_by_middleware(e,
request)

File "C:\Python36\lib\site-packages\django\core\handlers\base.py" in
_get_response
185. response = wrapped_callback(request, *callback_args,
**callback_kwargs)

File "C:\djangoprojects\mysite\mysite\core\views.py" in upload_files
92. document.save()

File "C:\Python36\lib\site-packages\django\db\models\base.py" in save
806. force_update=force_update,
update_fields=update_fields)

File "C:\Python36\lib\site-packages\django\db\models\base.py" in save_base
836. updated = self._save_table(raw, cls, force_insert,
force_update, using, update_fields)

File "C:\Python36\lib\site-packages\django\db\models\base.py" in _save_table
922. result = self._do_insert(cls._base_manager, using,
fields, update_pk, raw)

File "C:\Python36\lib\site-packages\django\db\models\base.py" in _do_insert
961. using=using, raw=raw)

File "C:\Python36\lib\site-packages\django\db\models\manager.py" in
manager_method
85. return getattr(self.get_queryset(), name)(*args,
**kwargs)

File "C:\Python36\lib\site-packages\django\db\models\query.py" in _insert
1060. return
query.get_compiler(using=using).execute_sql(return_id)

File "C:\Python36\lib\site-packages\django\db\models\sql\compiler.py" in
execute_sql
1099. cursor.execute(sql, params)

File "C:\Python36\lib\site-packages\django\db\backends\utils.py" in execute
80. return super(CursorDebugWrapper, self).execute(sql,
params)

File "C:\Python36\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)

File "C:\Python36\lib\site-packages\django\db\utils.py" in __exit__
94. six.reraise(dj_exc_type, dj_exc_value, traceback)

File "C:\Python36\lib\site-packages\django\utils\six.py" in reraise
685. raise value.with_traceback(tb)

File "C:\Python36\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)

File "C:\Python36\lib\site-packages\django\db\backends\sqlite3\base.py" in
execute
328. return Database.Cursor.execute(self, query, params)

Exception Type: IntegrityError at /core/upload_files/
Exception Value: UNIQUE constraint failed: core_profile.user_id


some of my code :

models:

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birth_date = models.DateField(null=True, blank=True)
birth_place = models.CharField(max_length=80, verbose_name= ("Lieu de
Naissance"))
email_confirmed = models.BooleanField(default=False)
adress = models.CharField(max_length=80, verbose_name=("Adresse"))
adress_complement = models.CharField(max_length=80, verbose_name=
("Complément d'Adresse"))
city = models.CharField(max_length=80, verbose_name=("Ville"))
zip_code = models.IntegerField(null=True, blank=True)
drive_licence_num = models.CharField(max_length=80, verbose_name=("N° du
Permis de conduire"))
social_secu_num = models.IntegerField(null=True, blank=True)
phone_number = models.IntegerField(null=True, blank=True)
profile_completed = models.BooleanField(default=False)
#DOCUMENTS TO UPLOAD
id_card = models.FileField(('Carte Nationale d\'Identité'))
drive_licence = models.FileField(('Permis de conduire'))
police_record = models.FileField(('Casier judiciaire'))
medical_visit = models.FileField(('Visite médicale'))
rib = models.FileField(('Relevé d\'Identité Bancaire (RIB)'))
uploaded_at = models.DateTimeField(auto_now_add=True)
docs_are_checked = models.BooleanField(default=False)

def __str__(self):
return self.user.username

@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()


forms :

class SignUpForm(UserCreationForm):
email = forms.EmailField(max_length=254, help_text='Required. Inform a
valid email address.')
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password1',
'password2',)

class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('birth_date','birth_place', 'adress', 'adress_complement',
'city', 'zip_code', 'drive_licence_num',
'social_secu_num','phone_number')

class DocumentForm(forms.ModelForm):
id_card = forms.FileField(('Carte Nationale d\'Identité'),
help_text='Required. Recto / Verso.')
class Meta:
model = Profile
fields = ('id_card', 'drive_licence',
'police_record', 'medical_visit', 'rib',)


views:

def complete_profile(request):
if request.user.is_authenticated():
if request.method == 'POST':
form = ProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
profile = form.save(commit=False)
profile.profile_completed = True
profile.save()
return redirect('upload_files')
else:
form = ProfileForm()
return render(request, 'complete_profile.html', {'form': form})
else:
return redirect('login')

def upload_files(request):
if request.user.is_authenticated():
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
document = form.save(commit=False)
document.user = request.user
document.save()
return render(request, 'home.html')
else:
form = DocumentForm()
return render(request, 'upload_files.html', {'form': form})
else:
return render(request, 'login.html')

Answer Source

I can't explain exactly why you are getting the error. However, since you are creating the profile in your signal handler, I think you should pass the instance to the form. This means you no longer have to set document.user in the if form.is_valid() block.

if request.method == 'POST':
    form = DocumentForm(request.POST, request.FILES, instance=request.user.profile)
    if form.is_valid():
        document = form.save()
        return render(request, 'home.html')
else:
    form = DocumentForm(instance=request.user.profile)

Note that it is recommended to redirect the user after a successful post request, to prevent duplicate submissions.

if form.is_valid():
    document = form.save()
    return redirect('/')