IntegrityError at /
UNIQUE 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:
UNIQUE constraint failed: pages_profile.username
How would you update an Abstractuser's custom avatar field? Specifically obj = Profile.objects.create(avatar = img)
from django.shortcuts import redirect, render
from .forms import UserProfileForm
from .models import Profile
def index(request):
context = {}
if request.method == "POST":
form = UserProfileForm(request.POST, request.FILES)
if form.is_valid():
img = form.cleaned_data.get("avatar")
obj = Profile.objects.create(
avatar = img
)
obj.save()
print(obj)
return redirect(request, "home.html", obj)
else:
form = UserProfileForm()
context['form']= form
return render(request, "home.html", context)
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class Profile(AbstractUser):
""" bio = models.TextField(max_length=500, blank=True)
phone_number = models.CharField(max_length=12, blank=True)
birth_date = models.DateField(null=True, blank=True) """
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',)
def clean_avatar(self):
avatar = self.cleaned_data['avatar']
try:
w, h = get_image_dimensions(avatar)
#validate dimensions
max_width = max_height = 1000
if w > max_width or h > max_height:
raise forms.ValidationError(
u'Please use an image that is '
'%s x %s pixels or smaller.' % (max_width, max_height))
#validate content type
main, sub = avatar.content_type.split('/')
if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']):
raise forms.ValidationError(u'Please use a JPEG, '
'GIF or PNG image.')
#validate file size
if len(avatar) > (20 * 1024):
raise forms.ValidationError(
u'Avatar file size may not exceed 20k.')
except AttributeError:
"""
Handles case when we are updating the user profile
and do not supply a new avatar
"""
pass
return avatar
CodePudding user response:
The error
IntegrityError at /
UNIQUE constraint failed: pages_profile.username
is implying that there is already another profile object with the same username that you are trying to create.
To fix this you need to update the existing profile if it already exists.
You can use django's create_or_update
like so
obj, created = Profile.objects.update_or_create(
username=form.cleaned_data.get('username'),
defaults={'avatar': img},
)
this will make django update any existing Profile object with username=form.cleaned_data.get('username')
if such a profile object does not exist, then it will be created.