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
How do I update an abstractuser from a post request using a form that's already signed in?
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',)
CodePudding user response:
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)
I swapped it to this and it just works but it doesn't delete the old photo in the s3 bucket yet. It was instance=request.user which was needed.