python – 如何在调用is_valid()方法后更改表单字段值?

如何在调用is_valid()方法后更改表单字段值?

我在使用form.is_valid验证数据后尝试更改字段u_id(这是必需的).我可以改变数据,甚至在HttpResponse中显示它,但我不能把它写入我的Postgresql DB.有任何想法吗?

class ProductForm(forms.ModelForm):
    class Meta:
            model = Product

class Product(models.Model):
    p_name = models.CharField(max_length=30)
    u_id = models.CharField(max_length=80)

def uploadImage(request):
    if request.method == 'POST':
        form1 = ProductForm(request.POST, prefix="product")
        if form.is_valid() and form1.is_valid():
            form1.cleaned_data['uid']='12134324231'
            form1.save()

            return HttpResponse(form1.cleaned_data['p_name'])

    return render_to_response('upload.html', {'form': form, 'form1': form1},            RequestContext(request))

最佳答案
Save the model form with commit = False,然后在保存到数据库之前修改实例.

if form.is_valid() and form1.is_valid():
    instance = form1.save(commit=False)
    instance.uid = '12134324231'
    instance.save()

如果form1具有任意多对多关系,则必须调用save_m2m方法来保存多对多表单数据.有关详细信息,请参阅文档.

点赞