0

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?

dfrojas
  • 673
  • 1
  • 13
  • 32
  • 1
    Are you using a `ModelForm`? Also, It is not required to do `form.save(commit=False)`. You can just call `form.save()` then all data including the many-to-many data to be save. – Rod Xavier Apr 20 '15 at 03:01
  • @RodXavier Yes, its a ModelForm, I tried already only with form.save() but does not save `def form_valid(self,form): form.save() return super(ProductorPropietarioView,self).form_valid(form)` – dfrojas Apr 20 '15 at 03:14
  • Can you post you form and the models concerned here? – Rod Xavier Apr 20 '15 at 03:15

1 Answers1

2

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)
Dan Russell
  • 960
  • 8
  • 22