On Thu, 2009-01-22 at 03:54 -0800, Lee wrote:
> Hi, Malcolm
> 
> Thanks for you reply. However, I'm still not clear.
> 
> My code is :
> 
> from django import forms
> 
> class TestForm(forms.Form):
>   title = forms.CharField( max_length=10 )
>   selection = forms.CharField( widget=forms.Select )
> 
> f = TestForm(initial={"title": 'Test', 'selection':{'1':'a','2':'b'}})

Since you haven't specified any choices for the form field, this isn't
going to be very useful. The initial values for any multiple choice
field (like Select) have to be a subset of the choices that the field
provides. Since your field provides precisely no choices, your initial
data for the "selection" attribute will have no effect.

The output you are seeing when you print this form is correct, based on
what you have told the form you want.

> print f
> 
> I want output like:
> 
> <option value="1">a</option>
> <option value="2">b</option>

For a start, that isn't a valid HTML form. The option elements have to
be wrapped inside something. Do you mean that is what you are hoping to
see for the "selection" field? If so, specifying some choices will
certainly help things along.

Either you have to write (just writing out the "selection" line):

        selection = forms.CharField(widget=forms.Select(
                            choices={'1': 'a', '2': 'b'})
        
or you need to set up the "choices" attribute as part of your form's
__init__ method. By default, you cannot modify the choices for a form
field via the constructor, only the initial values that are selected
("initial" for a form means the initial set values, not all the
possibilities).

Thus, if you want to pass in the choices, you have to write code to do
that yourself. For example:

        class TestForm(forms.Form):
           def __init__(self, *args, **kwargs):
              choices = kwargs.pop('choices')
              super(TestForm, self).__init__(*args, **kwargs)
              self.fields["selection"].widget.choices = choices
        
           # ...
        
and then TestForm(choices={...}) will set up the choices.

Regards,
Malcolm


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to