ModelForm with OneToOneField in Django

家住魔仙堡 提交于 2019-11-27 11:56:46

You have to create second form for PrinterAddress and handle both forms in you view:

if all((profile_form.is_valid(), address_form.is_valid())):
    profile = profile_form.save()
    address = address_form.save(commit=False)
    address.printer_profile = profile
    address.save()

Of course in the template you need to show both forms under one <form> tag :-)

<form action="" method="post">
    {% csrf_token %}
    {{ profile_form }}
    {{ address_form }}
</form>
NBajanca

Complementing the accepted answer:

If you have custom clean methods, you need to add a try/except case. For the example presented if address had a clean() method to validate something you needed to change it to:

def clean(self):
    try:
        printer_profile = self.printer_profile 
    except ObjectDoesNotExist:
        pass
    else:
        ...code to validate address...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!