gpt4 book ai didi

python - 在 Django 中更新字段不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 03:14:42 25 4
gpt4 key购买 nike

我的 views.py 中有以下内容

if request.method=='POST':
form = ExtraForm(request.POST,instance=request.user)
print ("hi")
if form.is_valid():
form.save()
print ("yes")
print ("newform is ")
else:
form = ExtraForm(instance=request.user)
context['form']=form
return render(request, "updateProfile.html",context)

现在发生的是,我没有收到任何错误,它做的一切都很好,但它最终没有更新任何东西!!这对我来说没有意义。知道发生了什么事吗?

额外形式:

class ExtraForm(forms.ModelForm):
research_place = forms.CharField(max_length=256, label="", required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'First Name','required':True}))
studies = forms.CharField(max_length=256, label="", required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'Last Name','required':True}))

class Meta:
model = RegisterUser
fields = ['research_place','studies']
widgets = {
# 'image': ImageCropWidget,
}

模型:

class RegisterUser(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)

biography = models.CharField(max_length=1000000,blank=True)
research_place = models.CharField(max_length=1000000,blank=True)
studies = models.CharField(max_length=1000000,blank=True)

image = models.ImageField(blank=True,null=True,upload_to='uploaded_images',default ="uploaded_images/defaultReal.jpg")
# cropping = ImageRatioField('image','200x200',size_warning=True) #width x height

avatar_thumbnail = ImageSpecField(source='image',
processors=[ResizeToFill(200, 200)],
format='JPEG',
options={'quality': 60})

activation_key = models.CharField(max_length=50)
key_expires = models.DateTimeField()
class Meta:
permissions = (
("has_uploaded", ("Has uploaded")),
("is_authenticated", ("Is authenticated")),
)

最佳答案

看起来表单根本无效。添加一个 else 子句并检查 errors :

if request.method == "POST":
form = ExtraForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
# You should perform some redirection here btw.
return redirect("/success/")
else:
print "Errors:", form.errors
context["form"] = form
else:
form = ExtraForm(instance=request.user)
context["form"] = form
return render(request, "updateProfile.html", context)

更新后:

您向表单传递了错误的用户。 request.userUser 类型,而您尝试更新 RegisteredUser。您应该更新行:

form = ExtraForm(request.POST, instance=request.user)

form = ExtraForm(request.POST, instance=RegisteredUser.objects.get(user=request.user))

同样适用于 else 部分:

form = ExtraForm(instance=RegisteredUser.objects.get(user=request.user))

关于python - 在 Django 中更新字段不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36670143/

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