在Django中更新字段不起作用

时间:2016-04-16 21:43:53

标签: python django forms field

我的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)

现在发生的事情是我没有得到任何错误,并且它完美地完成了一切,但它并没有最终更新任何东西!这对我没有意义。知道发生了什么事吗?

ExtraForm:

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")),
        )

1 个答案:

答案 0 :(得分:2)

表单看起来根本无效。添加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.user类型为User,而您尝试更新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))