Jun 5, 2010

MultipleChoiceField Django field with select multiple

Yesterday I was trying to find a way to use MultipleChoiceField Django field along with a CheckboxSelectMultiple Django widget for an input form that contains some tags used in an App Engine model field.
There is an excellent solution described in ( better-way-to-use-djangos-selectmultiple-in-google-app-engine-for-a-listproperty/) except that it relies on
google-app-engine-django package which is a nice package bridging App Engine db models and Django models.
But ... for this particular case I needed a light solution with a very small footprint and a minimum of imports.
It was more easy than I though.
First define our input choices and respective labels : tagChoises = ( ('Tag 1', 'Economy'), ('Tag 2','Geograpy'))
Then define your form item: tags = forms.MultipleChoiceField(required=False, choices=tagChoises , widget=forms.CheckboxSelectMultiple)
The form now displays the check boxes which a user can fill.
Problem is, if a user selects multi tags only the one is returned for saving into the db and since this value is a unicode string while a list of string values is expected it results in an form error.
Solution: intercept the retrurned value in Request Handler post this is a UnicodeMultiDict .
It turns out that getall method of this class returns a list of the selected strings so last item of code : self.request.POST['tags']=self.request.POST.getall('tags' ) makes the trick and posted values are ready to be put.
I know this is an ungly hack but still it is ok for situations where the complete Django package is an overkill.

4 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. Your hack makes sense, but i'm unable to validate teh form anyway. Keeps saying:

    "Items in the OBJECT list must all be Key instances"

    Any advice?

    ReplyDelete
  4. Sorry for late reply!
    May be I can help if you can provide some code.
    Regards
    Nick

    ReplyDelete