gpt4 book ai didi

python - 查看函数: saving a form field value into the profile model attribute

转载 作者:行者123 更新时间:2023-12-01 07:34:50 26 4
gpt4 key购买 nike

我正在 django 应用程序“colortest”中为我的 View 函数编写代码,我的配置文件模型位于 django 应用程序“users”中。我想将表单字段数据添加到配置文件模型属性中。当我保存变量时,我收到一个 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)

我希望将数据保存在配置文件模型的 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)

最佳答案

您正尝试在每次保存表单时创建新的配置文件。这是哪一行:

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')

关于python - 查看函数: saving a form field value into the profile model attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57032109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com