[英]How can I change form field values after calling the is_valid() method?
How can I change form field values after calling the is_valid()
method?调用
is_valid()
方法后如何更改表单字段值?
I am trying to alter the field u_id
after I validate the data with form.is_valid
(this is required).我试图改变场
u_id
我验证的数据后form.is_valid
(这是必需的)。 I can alter the data, even display it in the HttpResponse
, but I cannot write it into my Postgresql DB.我可以更改数据,甚至将其显示在
HttpResponse
,但我无法将其写入我的 Postgresql 数据库。 Any ideas?有什么想法吗?
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
, then modify the instance before saving to the database.使用
commit=False
保存模型表单,然后在保存到数据库之前修改实例。
if form.is_valid() and form1.is_valid():
instance = form1.save(commit=False)
instance.uid = '12134324231'
instance.save()
If form1
had any many-to-many relationships, you would have to call the save_m2m
method to save the many-to-many form data.如果
form1
有任何多对多关系,则必须调用save_m2m
方法来保存多对多表单数据。 See the docs for full details.有关完整详细信息,请参阅文档。
From Overriding clean() on a ModelFormSet .从在 ModelFormSet 上覆盖 clean() 。
Also note that by the time you reach this step, individual model instances have already been created for each Form.
另请注意,当您到达此步骤时,已经为每个表单创建了单独的模型实例。 Modifying a value in form.cleaned_data is not sufficient to affect the saved value.
修改 form.cleaned_data 中的值不足以影响保存的值。 If you wish to modify a value in ModelFormSet.clean() you must modify form.instance :
如果您希望修改 ModelFormSet.clean() 中的值,您必须修改 form.instance :
from django.forms import BaseModelFormSet
class MyModelFormSet(BaseModelFormSet):
def clean(self):
super(MyModelFormSet, self).clean()
for form in self.forms:
name = form.cleaned_data['name'].upper()
form.cleaned_data['name'] = name
# update the instance value.
form.instance.name = name
So what you should do is:所以你应该做的是:
if form.is_valid() and form1.is_valid():
form1.instance.uid ='12134324231'
form1.save()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.