Django.db.utils.IntegrityError: (1062, "Duplicate entry '8d4d1c76950748619f93ee2bfffc7de5' for key 'request_id'")

I don't understand what kind of error is ? sometimes this code works and after 1-2 times submitting form then trying to submit form again with different details then i got this error, django.db.utils.IntegrityError: (1062, "Duplicate entry '8d4d1c76950748619f93ee2bfffc7de5' for key 'request_id'")

Here this is my views.py code


@api_view(['POST', 'GET'])
def add_info_view(request):

    if request.method == 'POST':
        form = GitInfoForm(request.POST)
        if form.is_valid():
            form.save()
            try:
                git_Id = form.cleaned_data['git_Id']
                s = Gitinformation.objects.filter(git_Id=git_Id).values('request_id')
                print('Value of S :', s[0]['request_id'])
                s = s[0]['request_id']

                approve_url = f"http://127.0.0.1:8000/Approve/?request_id={str(s)}"
                print("Url : ", approve_url)
                try:
                    send_mail(
                        'KSA Test Activation',
                        approve_url,
                        'Noreplygcontrol@airlinq.com',
                        ['sorav.parmar@airlinq.com'],
                        fail_silently=False,
                    )
                    request.session['approve_url'] = approve_url
                    print('Approve Url sent : ', approve_url)
                except Exception as e:
                    pass
            except Exception as e:
                pass
        form = GitInfoForm()
    form = GitInfoForm()
    return render(request, 'requestApp/addInfo.html', {'form': form})



How to getrid of this error, please help me.

Based on your comment.

request_id = models.UUIDField(primary_key=False, default=uuid.uuid4().hex, editable=False, unique=True)

You assigned an instance of the UUID for the default value. In fact, you didn't set a function to generate a new UUID for each record. If you check the related migration file, you can see a line like this:

('request_id', models.UUIDField(default='97c8a76eefe8445081fcfec3af4f1df2', editable=False, unique=True))

you set an instance of the UUID as default but the unique property is set, because of this, the first time you save a record is ok but the next record, you face with error.

Actually, you have to set a function for the default to run for each record. You should set the properties like the below:

request_id = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False, unique=True)
Back to Top