Save m2m in FormView django

2019-09-16 15:28发布

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条回答
The star\"
2楼-- · 2019-09-16 15:35

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)
查看更多
登录 后发表回答