Search code examples
pythondjangoformsmodels

How do I make a form that creates a new related model object that is to be used on that same form?


Ok, that question I'm sure was confusing. Imagine we have this models:

class Phone(models.Model):
    serial = models.CharField(max_length=13, unique=True)
    model = models.CharField(max_length=4, choices=MODELOS)

class Contract(models.Model):
    number = models.IntegerField()
    phone = models.OneToOneField(Phone)
    notes = models.TextField(blank=True, null=True)
    sign = models.BooleanField(default=False)

I need to make a form which can have input for all the fields in those models. In one single page I need to specify the phone's serial and model and the contract's number, notes and sign. The phone field should be the one created in the same moment. How would I manage to do this?

Thank you!


Solution

  • As ilvar suggests, define two modelforms

    class PhoneForm(forms.ModelForm):
        class Meta:
            model = Phone
    
    class ContractForm(forms.ModelForm):
        class Meta:
            model = Contract
            exclude = ('phone',)
    
    def add(request):
       ...
       if request.method == 'POST':
           phone_form = PhoneForm(request.POST)
           contract_form = ContractForm(request.POST)
           if phone_form.is_valid() and contract_form.is_valid():
               phone = phone_form.save()
               contract = contract_form.save(commit=False)
               contract.phone = phone
               contract.save()
       ...
    

    Also, just curious why you use OneToOneField instead of ForeignKey or ManyToManyField, anyway.