How can create a model form in django with a one-to-one relation with another model

后端 未结 1 1636
走了就别回头了
走了就别回头了 2020-12-22 04:57

I want to create a model form with a one-to-one relation with another model. i.e Model1 has a one-to-one relation with Model2. I want my form to show all the fields from Mod

1条回答
  •  醉梦人生
    2020-12-22 05:16

    You don't need to create the single form for two models. Use two django forms and place them inside the single

    tag:

    class Model1Form(forms.ModelForm):
        class Meta:
            model = Model1
    
    class Model2Form(forms.ModelForm):
        class Meta:
            model = Model2
            exclude = ('model1_one_to_one_field', )
    
    def create_models(request):
        if request.method == 'POST':
            form1 = Model1Form(request.POST)
            form2 = Model2Form(request.POST)
            if all([form1.is_valid(), form2.is_valid()]):
                model1 = form1.save()
                model2 = form2.save(commit=False)
                model2.model1_one_to_one_field = model1
                model2.save()
                return redirect('create_models_success')
        else:
            form1 = Model1Form()
            form2 = Model2Form()
        return render(request, 'create_models.html',
                          {'form1': form1, 'form2': form2})
    

    And then the create_models.html template:

    
        {% csrf_token %}
        {{ form1.as_p }}
        {{ form2.as_p }}
        
    
    

    0 讨论(0)
提交回复
热议问题