Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing arguments to a dynamic form in django

Tags:

I have a Dynamic Form in forms. How can I pass an argument from my view when I instantiate my form?

Something like:

form = DynamicForm("some string argument I'm passing to my form") 

This is the form I have:

class DynamicForm(Form): def __init__(self, *args, **kwargs):     super(DynamicForm, self).__init__(*args, **kwargs)     for item in range(5):         self.fields['test_field_%d' % item] = CharField(max_length=255) 
like image 905
user140736 Avatar asked Feb 10 '10 13:02

user140736


1 Answers

Add it as keyword argument, say it's called my_arg. Make sure to pop() the keyword arg before calling super(), because the parent class's init method doesn't accept extra keyword arguments.

class DynamicForm(Form):   def __init__(self, *args, **kwargs):     my_arg = kwargs.pop('my_arg')     super(DynamicForm, self).__init__(*args, **kwargs)     for item in range(5):         self.fields['test_field_%d' % item] = CharField(max_length=255) 

And when you create form it's like this:

form = DynamicForm(..., my_arg='value') 
like image 173
gruszczy Avatar answered Oct 10 '22 07:10

gruszczy