简体   繁体   English

Django:如何在文本输入字段中显示值列表?

[英]Django: How can I show a list of values in a text input field?

I have defined a Model with a ManyToManyField, and I want the field to show the values joined by spaces, for example: 我已经定义了一个具有ManyToManyField的模型,并且我希望该字段显示由空格连接的值,例如:

<input type="text" name="foo" value="val1 val2 val3"/>

I have defined the form to use CharField to represent the multiple values: 我定义了使用CharField表示多个值的形式:

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()
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM