views.py
def get_form_initial(self, step):
if 'pk' in self.kwargs:
return {}
return self.initial_dict.get(step, {})
def get_form_instance(self, step):
if 'pk' in self.kwargs:
pk = self.kwargs['pk']
resume = Resume.objects.get(id=pk)
if step == 'resumes':
return resume
if step == 'work_experience':
work_experience = resume.workexperience_set.all()
return work_experience
if step == 'certifications':
certification = resume.certification_set.all()
return certification
if step == 'education':
education = resume.education_set.all()
return education
if step == 'skills':
skill = resume.skill_set.all()
return skill
if step == 'languages':
language = resume.language_set.all()
return language
return None
嗨!我有一个表单向导,每个步骤都可以使用不同的模型。我上面有代码可以为表单向导的每个步骤设置初始数据。
当我保存最后一个表单时,它将在数据库中创建模型的新实例。一些问题:
如何获取它来保存模型的当前实例/ id,而不是创建新实例/ id?
为什么即使我没有通过URL将kwargs中的任何PK传递给get_form_instance中的“如果self.kwargs”中的“ pk”也执行了代码?
在完成方法中,我将执行以下操作:
views.py
work_experience_form_data = self.get_cleaned_data_for_step('work_experience')
for work_experience in work_experience_form_data:
WorkExperience.objects.create(position=work_experience.get('position'),
company=work_experience.get('company'),
city=work_experience.get('city'),
start_date=work_experience.get('start_date'),
end_date=work_experience.get('end_date'),
achievements=work_experience.get('achievements'),
resume=resume, )