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 code

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

    if request.method == 'POST':
        form = GitInfoForm(request.POST)
        if form.is_valid():
                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"{str(s)}"
                print("Url : ", approve_url)
                        'KSA Test Activation',
                    request.session['approve_url'] = approve_url
                    print('Approve Url sent : ', approve_url)
                except Exception as e:
            except Exception as e:
        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