Save m2m in FormView django

无人久伴 提交于 2020-01-07 04:22:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!