问题
I'm trying to save a m2m field in a FormView
.
Here is my code:
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)
models.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__'
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()
What am I doing wrong?
回答1:
Try changing your FormView
as follows:
def form_valid(self,form):
f = form.save(commit=False)
f.save()
form.save_m2m()
return super(ProductorPropietarioView,self).form_valid(form)
来源:https://stackoverflow.com/questions/29738581/save-m2m-in-formview-django