ModelForm with OneToOneField in Django

前端 未结 2 1454
情深已故
情深已故 2020-12-02 15:42

I have two models in Django that are related with a OneToOneField (PrinterProfile and PrinterAdress). I am trying to do a form with

相关标签:
2条回答
  • 2020-12-02 16:23

    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...
    
    0 讨论(0)
  • 2020-12-02 16:31

    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>
    
    0 讨论(0)
提交回复
热议问题