Receive unicode rather than my object when saving a CheckBoxSelectMultiple
I'm using a CheckBoxSelectMultiple to display a list of stuff for the user to pick from. When I try to save, it gives me the error:
'unicode' object has no attribute 'name'
My choices list has 2-tuples, the first item being my custom object to be saved, and the second item being the human readable version (string).
forms.py:
# I have a list of my custo开发者_开发百科m objects here, which is built dynamically
data = grab_data()
# Building the choice list
CHOICES = []
for item in data:
CHOICES.append((item, item.name))
class DisplayForm(forms.Form):
display = forms.MultipleChoiceField(choices=CHOICES, widget=widgets.CustomCheckboxSelectMultiple())
This is the views:
views.py:
....
if forms.is_valid():
items = request.POST.getlist('display')
for item in items:
print type(item) # Says it's unicode, not my custom object that I want to add to my model.
mymodel = PackageModel(name=item.name, etd=item.etd) # breaks here since 'item' is unicode object and not my custom object
mymodel.save()
....
Looking at the CheckboxSelectMultiple source code (very similar to my custom one that I used), I thought it was on line 706, where it tries to force unicode on the option_value, which I think is supposed to be my custom object. Removing that doesn't help though.
Here is the link to the source on Django:
https://code.djangoproject.com/browser/django/trunk/django/forms/widgets.py
You're going to get back a list of the values from your items, not the objects themselves. You'll need to instantiate those objects from the values in the items list on your own.
Because you're inheriting from forms.Form instead of forms.ModelForm, Django isn't going to instantiate objects from the values in your items list.
精彩评论