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
您將如何更新 Abstractuser 的自定義頭像欄位?具體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)
模型.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)
表格.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
uj5u.com熱心網友回復:
錯誤
IntegrityError at /
UNIQUE constraint failed: pages_profile.username
暗示已經有另一個組態檔物件與您嘗試創建的用戶名相同。
要解決此問題,您需要更新現有組態檔(如果它已經存在)。
你可以create_or_update像這樣使用django
obj, created = Profile.objects.update_or_create(
username=form.cleaned_data.get('username'),
defaults={'avatar': img},
)
這將使 django 更新任何現有的 Profile 物件 username=form.cleaned_data.get('username')
如果這樣的組態檔物件不存在,則將創建它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389611.html
標籤:姜戈
上一篇:型別錯誤:欄位'id'需要一個數字,但得到了(<Group:customer>,True)DJANGO錯誤
下一篇:將日期插入資料庫時??丟失微秒
