Reputation: 992
Basically I'm trying to create some sort of dynamic form and I'm trying to change the value of a CharField via a post request. Simply, I have the following field in my form:
choice = forms.CharField(max_length=50)
In the init of the form I have something like this:
for key, value in request.post.items():
if key == 'choice' and value != '':
self.fields['choice'] = value
That obviously does not work because I'm assigning a string (value) to a CharField (choice). Any ideas are greatly appreciated.
Upvotes: 2
Views: 4648
Reputation: 599530
It depends on what you mean by the 'value' of the field.
If you're trying to change what is shown when the form is displayed initially, you need to pass an initial
dictionary with a key corresponding to the field name:
self.initial['choice'] = 'myvalue'
If you're trying to change what gets passed into validation and then to cleaned_data
, you need to change the data
parameter:
self.data['choice'] = 'myvalue'
Upvotes: 3
Reputation: 25936
Are you looking for something along the lines of http://jacobian.org/writing/dynamic-form-generation/?
in the example it adds X number of char fields via the init
for i, question in enumerate(extra):
self.fields['custom_%s' % i] = forms.CharField(label=question)
Should be able to extend extra for different form fields.
Upvotes: 1