我正在为django应用程序“colortest”中的views函数编写代码,我的配置文件模型在django应用程序“users”中。我想在Profile Model属性中添加表单字段数据。当我保存变量时,我得到一个IntegrityError
我搜索了每个网站,但我不明白
颜色测试/views.py
from users.models import Profile
def testreport(request):
if request.method == "POST":
test_result = request.POST.get('test_result')
p = Profile(user=request.user, test_result=test_result)
p.save()
messages.success(request, f'Your account has been Updated!')
return render(request, 'colortest/test1.html')
return render(request, 'colortest/result.html')
用户/模型.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
bio = models.TextField(max_length=1000, default="")
test_result = models.CharField(max_length=100, default="")
def __str__(self):
return f'{self.user.username} Profile'
def save(self, *args, **kwargs):
super(Profile, self).save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
我希望数据保存在Profile模型的test\u result字段中 但它不断地给出错误
IntegrityError at /colortest/result/testreport
UNIQUE constraint failed: users_profile.user_id
Request Method: POST
Request URL: http://127.0.0.1:8000/colortest/result/testreport
Django Version: 2.2.1
Exception Type: IntegrityError
Exception Value:
UNIQUE constraint failed: users_profile.user_id
C:\Users\Osama E.Khan\Desktop\website\colortest\views.py in testreport
p.save() …
▶ Local vars
C:\Users\Osama E.Khan\Desktop\website\users\models.py in save
super(Profile, self).save(*args, **kwargs)
每次保存表单时,您都试图创建一个新的配置文件。这是哪一行:
每次都将创建该配置文件的新实例。您需要更改该行以检查配置文件是否已经存在。重新使用现有配置文件或创建新配置文件后,如果该配置文件不存在,则需要保存最新的测试结果,或重新建模保存方式,以便每次都将新的测试结果保存到配置文件中
更新
如果要更新到最新值,可以尝试获取最新值并进行更新:
相关问题 更多 >
编程相关推荐