开发者

How do I set a forms.CharField text programmatically?

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'] = val开发者_如何学Goue

That obviously does not work because I'm assigning a string (value) to a CharField (choice). Any ideas are greatly appreciated.


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'


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜