Dear All,
how to use inline form set. In Django documentation, there is only add the detail which related to master which already exists. How to add both master and detail at the same time using Inline form set.
best regards,
kimhong
Dear All,
how to use inline form set. In Django documentation, there is only add the detail which related to master which already exists. How to add both master and detail at the same time using Inline form set.
best regards,
kimhong
Step 1: Define Models
# models.py
from django.db import models
class Parent(models.Model):
name = models.CharField(max_length=100)
class Child(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE, related_name='children')
name = models.CharField(max_length=100)
Step 2: Create Forms and Formsets
# forms.py
from django import forms
from django.forms import inlineformset_factory
from .models import Parent, Child
class ParentForm(forms.ModelForm):
class Meta:
model = Parent
fields = ('name',)
class ChildForm(forms.ModelForm):
class Meta:
model = Child
fields = ('name',)
# Create inline formset for Child with respect to Parent
ChildInlineFormSet = inlineformset_factory(Parent, Child, form=ChildForm, extra=1, can_delete=True)
Step 3: Write Views
# views.py
from django.shortcuts import render, redirect
from django.urls import reverse
from .forms import ParentForm, ChildInlineFormSet
from .models import Parent
def add_parent_with_children(request):
if request.method == 'POST':
parent_form = ParentForm(request.POST)
child_formset = ChildInlineFormSet(request.POST)
if parent_form.is_valid() and child_formset.is_valid():
# Save the parent first
parent = parent_form.save()
# Then save the children, associating them with the parent
instances = child_formset.save(commit=False)
for instance in instances:
instance.parent = parent
instance.save()
# Handle any deleted children if the formset supports deletion
child_formset.save_m2m()
return redirect(reverse('some_success_url'))
else:
parent_form = ParentForm()
child_formset = ChildInlineFormSet()
return render(request, 'add_parent_with_children.html', {
'parent_form': parent_form,
'child_formset': child_formset,
})
Step 4: Create a Template
<!-- templates/add_parent_with_children.html -->
<form method="post">
{% csrf_token %}
{{ parent_form.as_p }}
{{ child_formset.management_form }}
<table>
{% for form in child_formset.forms %}
<tr>
<td>{{ form.id }}</td>
<td>{{ form.name }}</td>
<td>{{ form.DELETE }}</td>
</tr>
{% endfor %}
</table>
<button type="submit">Save</button>
</form>
Step 5: URL Configuration
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('add/', views.add_parent_with_children, name='add_parent_with_children'),
# Add your success URL here, e.g., path('success/', views.success_view, name='some_success_url')
]