Django: How can I show a list of values in a text input field?
I have defined a Model wit开发者_如何转开发h a ManyToManyField, and I want the field to show the values joined by spaces, for example:
<input type="text" name="foo" value="val1 val2 val3"/>
I have defined the form to use CharField to represent the multiple values:
class MyForm(ModelForm):
foo = CharField(label='Foo')
class Meta:
model = MyModel
Instead of showing the values separated by spaces, the value shows this instead:
[u'val1', u'val2', u'val3']
How can I override this behavior?
You have a basic misunderstanding, which is that fields themselves aren't responsible for how they're rendered. That's what widgets do.
Ok, I finally figured it out:
class MultiValueTextWidget(TextInput):
def _get_value(self, value):
return " ".join(value)
def _format_value(self, value):
if self.is_localized:
return formats.localize_input(self._get_value(value))
return self._get_value(value)
I had tried this earlier (before I posted the original question), but I think there was something wrong with my field declaration. It works when I instantiate the field with the widget like this:
markets = CharField(widget=MultiValueTextWidget(), label='Ticker symbols')
For some reason I had trouble with this:
class Meta:
widgets = {
'markets': MultiValueTextWidget()
}
精彩评论