دو فرم که با مدل های آنها با هم ارتباط دارند رو میشه توی یک فرم به شکل زیر ساخت:
1 2 3 4 5 6 7 8 9 10 |
class OfficeForm(ModelForm): class Meta: model = Office fields = ["name", "title_en", "title_fa", "branch"] class OfficeBossForm(ModelForm): class Meta: model = OfficeBoss fields = ["expert"] |
view باید به شکل زیر باشه
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
def office_add(request): if request.method == "POST": office_form = OfficeForm(request.POST) office_boss_form = OfficeBossForm(request.POST) else: office_form = OfficeForm() office_boss_form = OfficeBossForm() if request.method == "POST": if office_form.is_valid() and office_boss_form.is_valid(): office_instance = office_form.save(commit=False) office_boss_instance = office_boss_form.save(commit=False) office_boss_instance.office = office_instance office_instance.save() office_boss_instance.save() messages.success(request, '.....') return redirect('man:management_offices') return render(request, "man/office/office-add.html", { 'form': office_form, 'form2': office_boss_form }) |