Django.db.utils.IntegrityError: UNIQUE constraint failed OneToOneField Django

I have a problem with my database. I have two models (Member, ActiveMember) with a OneToOneField relationship setup. A member can only have one membership at a time. However, I seem to be getting a Unique error. Once I update my members membership using the update function things seems to get mixed up and the ID no longer work. I also get another error DoesNotExist. I think this happens with I delete a members and/or update, the ID's are shifting somehow. This Error I got when I tried to migrate. I had to delete the member the was causing me problems for it to work.

Running migrations:
  Applying members.0007_alter_activemember_member...Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: new__members_activemember.member_id
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/topxgym/.virtualenvs/env/topxgym/manage.py", line 22, in <module>
    main()
  File "/home/topxgym/.virtualenvs/env/topxgym/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 244, in handle
    post_migrate_state = executor.migrate(
  File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/usr/local/lib/python3.9/site-packages/django/db/migrations/migration.py", line 126, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/usr/local/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 244, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 140, in alter_field
    super().alter_field(model, old_field, new_field, strict=strict)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 594, in alter_field
    self._alter_field(model, old_field, new_field, old_type, new_type,
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 362, in _alter_field
    self._remake_table(model, alter_field=(old_field, new_field))
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 285, in _remake_table
    self.execute("INSERT INTO %s (%s) SELECT %s FROM %s" % (
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 145, in execute
    cursor.execute(sql, params)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute
    return super().execute(sql, params)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: new__members_activemember.member_id

This is the second Error DoesNotExist

Traceback (most recent call last):
  File "/home/topxgym/.virtualenvs/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/topxgym/.virtualenvs/env/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/topxgym/.virtualenvs/env/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/topxgym/.virtualenvs/env/topxgym/members/views.py", line 184, in update
    member = ActiveMember.objects.get(pk=id)
  File "/home/topxgym/.virtualenvs/env/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/topxgym/.virtualenvs/env/lib/python3.9/site-packages/django/db/models/query.py", line 650, in get
    raise self.model.DoesNotExist(

Exception Type: DoesNotExist at /update/7
Exception Value: ActiveMember matching query does not exist.

This is My models.py

class Member(models.Model):
    full_name = models.CharField(max_length=125, unique=True)    
    email = models.EmailField(max_length=125, blank=True, null=True)
    phone = models.CharField(max_length=20)
    detail = models.CharField(max_length=256, blank=True, null=True)
    image = models.ImageField(max_length= 256, upload_to='media', null=True, blank=True)
    date_created = models.DateTimeField(default=django.utils.timezone.now)

    class Meta:
        verbose_name_plural = "All Members"

    def __str__(self):
        return str(f"{self.full_name}")
    
    def save(self, *args, **kwargs):
        # delete old file when replacing by updating the file
        try:
            this = Member.objects.get(id=self.id)
            if this.image != self.image:
                this.image.delete(save=False)
        except: pass # when new photo then we do nothing, normal case          
        super(Member, self).save(*args, **kwargs)


class ActiveMember(models.Model):
    member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='is_member')
    start_date = models.DateField(default=django.utils.timezone.now)
    end_date = models.DateField(default=django.utils.timezone.now)
    status = models.CharField(max_length=2, choices=(('0','None'), ('1','Active'), ('2','Inactive')), default = '1')
    
    def __str__(self): 
        return str(f"{self.member}")

This is my views.py

@login_required(login_url='authenticate/admin_login')
def update(request, id):
    member = ActiveMember.objects.get(pk=id)
    if request.method == 'POST':
        form = ActiveMemberForm(request.POST, instance=member)
        if form.is_valid():
            # save form data to variables
            active_member = form.cleaned_data['member']
            start_date = form.cleaned_data['start_date']
            status = form.cleaned_data['status']

            # send WhatsApp message to inform user his membership has been activated.
            if  active_member.phone is not None and status == '1':
                msg = WhatsApp(active_member.full_name, active_member.phone, start_date)
                msg.send_message('customer_active')

            # save form to database.
            form.save()
            # redirect to the success message
            return render(request, 'members/update.html', {
                'form': form,
                'success': True,
            })
    else:
        form = ActiveMemberForm(instance=member)
    return render(request, 'members/update.html', {
        'form': form,
        'member': member,
        })

@login_required(login_url='authenticate/admin_login')
def delete(request, id):
    if request.method == 'POST':
        if request.user.is_superuser:
            member = Member.objects.get(pk=id)
            member.delete()
    return HttpResponseRedirect(reverse('members:index'))
Back to Top