Reputation: 78
I have a multiple modelforms form multiple model. I want one single CreateView for submitting all the values. I have three models(Employee, WorkExperience and Education). Models are connected using ForeignKey with each other.
forms.py:
class EmployeeAddModelForm(forms.ModelForm):
"""
Creates a form for employee invitations
"""
class Meta:
model = Employee
fields = [
'e_id',
'first_name',
'last_name',
'gender',
'religion',
]
class WorkExperienceForm(forms.ModelForm):
"""
Creates a form for saving employee work experiences
"""
class Meta:
model = WorkExperience
fields = [
'previous_company_name',
'job_designation',
'from_date',
'to_date',
'job_description',
]
class EducationForm(forms.ModelForm):
"""
Creates a form for saving educational info of an employee
"""
class Meta:
model = Education
fields = [
'institution_name',
'degree',
'passing_year',
'result',]
I have three model forms from three models in form.py. I want that my createview inherits all this modelforms and create a single form for posting data.
views.py:
class EmployeeAddView(LoginRequiredMixin,CreateView):
"""
Creates new employee
"""
login_url = '/authentication/login/'
template_name = 'employee/employee_add_form.html'
form_class = EmployeeAddModelForm
work_form_class = WorkExperienceForm
queryset = Employee.objects.all()
def form_valid(self, form):
print(form.cleaned_data)
return super().form_valid(form)
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
work_form = self.work_form_class(request.POST, prefix='work_form')
education_form = self.education_form_class(request.POST, prefix='education_form')
if form.is_valid() and work_form.is_valid():
instance = form.save()
work = work_form.save(commit=False)
education = education_form.save(commit=False)
work.employee = instance
education.employee = instance
work.save()
education.save()
if not education_form.is_valid():
print("Education")
return redirect('employee:employee-list')
def get_success_url(self):
return reverse('employee:employee-list')
I am rendering two forms from my view class. But when I use 'work_form' in my template.html, nothing appears.
How can I render all modelforms in my view?
Upvotes: 0
Views: 896
Reputation: 982
def get(self, request, *args, **kwargs):
form = self.form_class(**self.get_form_kwargs())
work_form = self.work_form_class(prefix='work_form')
return render(request, self.template_name, {'form': form, 'work_form': work_form})
Upvotes: 1