试图保存ManyToManyField

时间:2012-10-13 18:03:43

标签: django django-forms

  

可能重复:
  Django “Enter a list of values” form error when rendering a ManyToManyField as a Textarea

我在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 and 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

2 个答案:

答案 0 :(得分:1)

首先,你不应该用干净的方法保存东西。

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

答案 1 :(得分: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