在FormView Django中保存M2M [英] Save m2m in FormView django
本文介绍了在FormView Django中保存M2M的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 FormView
中保存一个m2m字段。
I'm trying to save a m2m field in a FormView
.
这是我的代码:
class ProductorPropietarioView(FormView):
form_class = FormPropietario
success_url = '/'
template_name = 'productores/propietario.html'
def form_valid(self,form):
form.save(commit=False)
form.save()
form.save_m2m()
return super(ProductorPropietarioView,self).form_valid(form)
模型.py
class Persona(models.Model):
predio = models.ForeignKey(InfoPredioGeneral,related_name='predio+')
rol = models.ManyToManyField(RolPersona)
tipo_identificacion = models.ForeignKey(TipoIdentificacion,related_name='tipo identificacion+',blank=True,null=True)
numero_identificacion = models.CharField(max_length=100,blank=True,null=True)
forms.py
class FormPropietario(ModelForm):
class Meta():
model = Persona
fields = '__all__'
我无法使用它。我知道,首先我必须设置False,然后保存表单,然后保存m2m。我已经只尝试了 form.save()
I can't get this to work. I know that first I have to set False then save the form and then save the m2m. I already tried only with form.save()
我在做什么错了?
推荐答案
尝试如下更改您的 FormView
:
def form_valid(self,form):
f = form.save(commit=False)
f.save()
form.save_m2m()
return super(ProductorPropietarioView,self).form_valid(form)
这篇关于在FormView Django中保存M2M的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文