abolotnov
abolotnov

Reputation: 4332

Django form initial data being set as lists

I am trying to set some initial form data with request.GET data when it's being initialized:

GET data:

http://localhost:8000/form_builder/SoW/create/?project=1&value=100

The form:

class SoWForm(forms.ModelForm):
    class Meta:
        model = SoW
        fields = (
            'project',
            'ref',
            'date_signed',
            'sow_file',
            'value',
            'status'
        )

    def __init__(self, *args, **kwargs):
        super(SoWForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)

Initialization of the form:

form = SoWForm(initial=request.GET)

What happens is that all form fields that are being set are being populated as lists:

form initial fields are populated as lists

and it breaks the form of course:

broken form data

Is there a way to avoid this? Does it dict(request.GET) somewhere on the way while trying to pick up the data and stuff?

dict(request.GET.iteritems()) will convert request.GET to a 'proper' dict for the initial data, but isn't default behavior wrong?

Upvotes: 1

Views: 396

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599778

The problem is not with the form, but with what you're using to populate it. QueryDicts are a special dict subclass intended to support the possibility of multiple values in the querystring or POST data, for example:

>>> QueryDict('a=1&b=2&b=3')
<QueryDict: {u'a': [u'1'], u'b': [u'2', u'3']}>

and, as you've discovered, that's not suitable for use as form initial data.

You've already found the workaround; I recommend you continue doing that.

Upvotes: 1

Related Questions