[Django]-Django temporary fields only upon creation

2👍

First of all, you here made two relations between Employee and Contract. Django automatically makes a relation in reverse, so you probably should remove one. Otherwise it is possible that some_contract.emplyee.contract is not the same as some_contract.

You thus for example might want to re-model this to:

class Employee(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)

class Contract(models.Model):
    employee = models.OneToOneField(Employee, on_delete=models.CASCADE, related_name='contract')
    contract_type = models.ForeignKey(ContractType, on_delete=models.CASCADE)
    start_date = models.DateField()
    end_date = models.DateField()

You can just create two ModelForms:

# app/forms.py

from app.models import Employee, Contract

class EmployeeForm(ModelForm):
    class Meta:
        model = Employee
        exclude = ['contract']

class ContractForm(ModelForm):
    class Meta:
        model = Contract

Then we can render the two forms:

# app/views.py

from django.shortcuts import redirect, render
from app.forms import EmployeeForm, ContractForm

def some_view(request):
    if request.method == 'POST':
        employee_form = EmployeeForm(request.POST)
        contract_form = ContractForm(request.POST)
        if employee_form.is_valid() and contract_form.is_valid():
            employee = employee_form.save()
            contract_form.instance.employee = employee
            contract_form.save()
            return redirect('some-view')
    else:
        employee_form = EmployeeForm()
        contract_form = ContractForm()
    return render(
        request,
        'some_template.html',
        {'employee_form': employee_form, 'contract_form': contract_form}
    )

in the template, we then render the two forms in the same <form> tag:

<!-- some_template.html -->
<form method="post">
    {% csrf_token %}
    {{ employee_form }}
    {{ contract_form }}
    <button type="submit">submit</button>
</form>

Leave a comment