在Django表单中,为了保存其他数据,我通常使用
今天,我重写了
当我使用
这是我重写的save()方法:
form_valid()
,但我也可以使用表单类的save()
方法。今天,我重写了
save()
而不是form_valid()
,遇到了关于manytomanyfield的问题。当我使用
save()
时,manytomanyfield的值没有被保存,但当我使用form_valid()
时,它们开始保存。有人能告诉我原因以及两种方法之间的区别是什么,哪种方法最方便,在什么情况下使用?这是我重写的save()方法:
class ProductCreateForm(forms.ModelForm):
sizes = make_ajax_field(ProductCreateModel,'sizes','sizes')
colours = make_ajax_field(ProductCreateModel,'colours','colours')
class Meta:
model = ProductCreateModel
fields = ('title','category',
'regions',)
def __init__(self,*args,**kwargs):
self.request = kwargs.pop("request")
super(ProductCreateForm, self).__init__(*args, **kwargs)
def save(self):
product = super(ProductCreateForm, self).save(commit=False)
user = self.request.user
product.location = user.user_location
product.save()
return product
当我重写 form_valid() 方法时:
def get_form_kwargs(self):
kwargs = super(ProductCreateView,self).get_form_kwargs()
kwargs.update({'request':self.request})
return kwargs
def form_valid(self, form):
product = form.save(commit=False)
user = self.request.user
form.instance.user = user
form.instance.location = user.user_location
form.save()
return super(ProductCreateView, self).form_valid(form)
sizes
, colours
和regions
是m2m字段,就像我在重写save()
时提到的一样,m2m值不会保存,但是当我重写form_valid
时,它们开始保存。