Building a formset dynamically
Posted
by vorpyg
on Stack Overflow
See other posts from Stack Overflow
or by vorpyg
Published on 2010-06-07T11:47:30Z
Indexed on
2010/06/07
11:52 UTC
Read the original article
Hit count: 338
I initially wrote code to build a form dynamically, based on data from the DB, similar to what I described in my previous SO post.
As SO user Daniel Roseman points out, he would use a formset for this, and now I've come to the realization that he must be completely right. :)
My approach works, basically, but I can't seem to get validation across the entire form to be working properly (I believe it's possible, but it's getting quite complex, and there has to be a smarter way of doing it => Formsets!).
So now my question is: How can I build a formset dynamically? Not in an AJAX way, I want each form's label to be populated with an FK value (team) from the DB.
As I have a need for passing parameters to the form, I've used this technique from a previous SO post.
With the former approach, my view code is (form code in previous link):
def render_form(request):
teams = Team.objects.filter(game=game)
form_collection = []
for team in teams:
f = SuggestionForm(request.POST or None, team=team, user=request.user)
form_collection.append(f)
Now I want to do something like:
def render_form(request):
teams = Team.objects.filter(game=game)
from django.utils.functional import curry
from django.forms.formsets import formset_factory
formset = formset_factory(SuggestionForm)
for team in teams:
formset.form.append(staticmethod(curry(SuggestionForm, request.POST or None, team=team, user=request.user)))
But the append bit doesn't work. What's the proper way of doing this?
Thanks!
© Stack Overflow or respective owner