Reputation: 68
I am using Django Formtools to create a multistep form for a Job posting process. In one of the forms, I have Job Questions which I want the user to add dynamically, say a checkbox that generates the question form if they are interested in adding questions. They should have a button to create as many questions as possible. Now my challenge is that when I use normal model forms, I am able to complete the job posting process but if i replace the question form with a model formset and include it in the form_list I get key errors.
Secondly, if I try the various Javascript responses on adding fields dynamically such as this stack overflow response, I get form validation errors. Just to mention, the question Form uses the same model as the other forms (Job Model) thus my expectation is that regardless of how many questions are added they will be save to the Job Model. Does anyone know how to go about this? Adding fields in Django formtools dynamically and saving to the model? My Form tools wizard looks as below:
class JobWizard(SessionWizardView):
form_list=[JobForm7,JobForm1,JobForm2,JobForm3, JobForm4,JobForm5,JobForm6 ]
file_storage= FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'jobs'))
template_name="jobs/jobforms.html"
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, form_dict, **kwargs):
form_dict = self.get_all_cleaned_data()
categories = form_dict.pop('categories')
sub_categories = form_dict.pop('sub_categories')
job_question = form_dict.pop('job_question')
print(job_question)
print("_________________________")
job=Job.objects.create(**form_dict)
job.categories=categories
job.job_question=job_question
for sub_category in sub_categories:
job.sub_categories.add(sub_category)
# for question in job_question:
# job.job_question.add(question)
job.save()
return redirect('job_list')
And my model looks as below:
class Job(models.Model):
...#Other fields
# Form 4
job_question=models.CharField(max_length=20, default="")
# Form 5
job_freelancers_number=models.IntegerField(default=1)
Upvotes: 0
Views: 691
Reputation: 68
So I was able to handle this by using Django Dynamic Formset library.All I needed was create the jquery.formset.js in my STATIC_URL then reference the same in my template after jquery. Then in my template < /script> section i passed below:
<script type="text/javascript">
$(function() {
$('#job-question').formset();
})
Upvotes: 1