Django 更新抽象用户

Django Update AbstractUser

IntegrityError at /
NOT NULL constraint failed: pages_profile.username
Request Method: POST
Request URL:    http://127.0.0.1:8000/
Django Version: 3.2.9
Exception Type: IntegrityError
Exception Value:    
NOT NULL constraint failed: pages_profile.username

如何使用已登录的表单从 post 请求更新抽象用户?

from django.shortcuts import redirect, render
from .forms import UserProfileForm
from .models import Profile

def index(request):
    context = {}

    if request.method == "POST":
        print(request.POST)
        form = UserProfileForm(request.POST, request.FILES)
        if form.is_valid():
            img = form.cleaned_data.get("avatar")
            obj, created = Profile.objects.update_or_create(
                username=form.cleaned_data.get('username'),
                defaults={'avatar': img},
            )
            obj.save()
            print(obj)
            return redirect('home')

    else:
        form = UserProfileForm()
    context['form']= form
    return render(request, "home.html", context)

urls.py

from django.urls import path
from pages.views import index

urlpatterns = [
    path('', index, name='home'), 
]

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class Profile(AbstractUser):
    
    avatar = models.ImageField(default='default.png', upload_to='',null=True, blank=True )

forms.py

from django import forms
from django.core.files.images import get_image_dimensions

from pages.models import Profile

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('avatar',)
from django.shortcuts import redirect, render
from .forms import UserProfileForm
from .models import Profile

def index(request):
    context = {}
    if request.method == "POST":
        print(request.POST)
        form = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user)
        if form.is_valid():
            """ 
            img = form.cleaned_data.get("avatar")
            print(img)
            print(form.cleaned_data.get('username'))
            print(request.user)
            obj, created = Profile.objects.update_or_create(
                username=form.cleaned_data.get('username'),
                defaults={'avatar': img},
            )
            obj.save()
            print(obj)
            """
            form.save()
            return redirect('home') 
    else:
        form = UserProfileForm(instance=request.user)
    context['form']= form
    return render(request, "home.html", context)

我把它换成了这个,它可以正常工作,但它还没有删除 s3 存储桶中的旧照片。需要的是 instance=request.user。