我正在django应用程序“ colortest”中为views函数编写代码,而我的Profile模型在django应用程序“ users”中。我想将表单字段数据添加到Profile Model属性中。当我保存变量时,我收到一个IntegrityError
我搜索了每个站点,但我听不懂
colortest / 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')
users / models.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 Model的test_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)
答案 0 :(得分:0)
每次保存表单时,您都试图创建一个新的配置文件。这是哪一行:
p = Profile(user=request.user, test_result=test_result)
这将每次创建该配置文件的新实例。您将需要更改该行以检查配置文件是否已存在。重新使用现有配置文件或创建新配置文件后,您将需要针对该配置文件保存最新的测试结果,或者重新建模其保存方式,以每次将新测试结果保存到配置文件中
更新
如果要更新为最新值,可以尝试获取最新值并进行更新:
def testreport(request):
if request.method == "POST":
test_result = request.POST.get('test_result')
try:
p = request.user.profile
except Profile.DoesNotExist:
p = Profile(user=request.user, test_result=test_result)
p.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')