0

可能重复:
将 ManyToManyField 呈现为 Textarea 时出现 Django“输入值列表”表单错误

我在输入字段中有python,django,ajax这些数据。artist我收到Enter a list of values.错误。你能帮我保存这些数据吗?谢谢

模型

artist = models.ManyToManyField(ApiArtist, blank=True)

表格和验证

class ApiSongForm(ModelForm):
    class Meta:
        model = ApiSong
        widgets = {
            'artist': forms.TextInput(),
        }

    def clean_artist(self):
        data = self.cleaned_data
        artist_list = data.get('artist', None)
        if artist_list is not None:
            for artist_name in artist_list.split(','):
                artist = ApiArtist(name=artist_name).save()
        return artist_list

编辑

现在我已经从提供的链接更改了代码复制/粘贴。但是,我得到了Cannot resolve keyword 'artist' into field. Choices are: apisong, id, name。错误信息。这是我的ApiArtist 和 SongModel。谢谢

class ModelCommaSeparatedChoiceField(ModelMultipleChoiceField):
    widget = forms.TextInput
    def clean(self, value):
        if value is not None:
            print value
            value = [item.strip() for item in value.split(",")]  # remove padding
        return super(ModelCommaSeparatedChoiceField, self).clean(value)

class ApiSongForm(ModelForm):
    artist = ModelCommaSeparatedChoiceField(
               required=False, queryset=ApiArtist.objects.filter(), to_field_name='artist')
    class Meta:
        model = ApiSong
4

2 回答 2

1

首先,您不应该在 clean 方法中保存东西。

其次,您的代码不会将文本输入中的值转换为列表。您的 if 语句中有一个split,但在返回结果之前您没有将结果设置回artist_list

于 2012-10-13T19:00:47.687 回答
1

现在我的以下代码正在运行。无论如何谢谢

class ApiSongForm(ModelForm):
    artist = forms.CharField()

    def save(self, commit=True):
        instance = super(ApiSongForm, self).save(commit=commit)
        artists = self.cleaned_data.get('artist', None)
        if artists is not None:
            for artist_name in artists.split(","):
                artist = ApiArtist.objects.create(name=artist_name)
                instance.artist.add(artist)

        instance.save()
        return instance
于 2012-10-14T08:18:52.763 回答