Will-Opare February 2016

Django 1.9: How to make a dynamic form?

I have a model called Course:

class Course(models.Model):
   number_of_semesters = models.PositiveIntegerField()
   field = models.CharField(max_length=30)
   qualification = models.ForeignKey(Qualification, on_delete=models.CASCADE)

I am trying to get a form in which you can input as many courses as the user wants from the webpage. How will I do this?

Answers


Rolf February 2016

One way you could do this is to not use formsets but to get creative with the prefix that you use to load a form with. For example the + button loads an empty form with a prefix based on a counter posted to the view (including a tag, something like "course-4", so you get the form with SomeForm(request.POST, prefix="course-4")). When it's time to validate/save the view you simply parse the prefixes (with a regex) from the POST and save a form for every one of them.

It seems like a bit more work than to simply use formsets but every time I've tried to use them I had to abandon them at some point because they didn't provide enough flexibility.

Post Status

Asked in February 2016
Viewed 2,124 times
Voted 6
Answered 1 times

Search




Leave an answer