首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >试图拯救ManyToManyField

试图拯救ManyToManyField
EN

Stack Overflow用户
提问于 2012-10-13 18:03:43
回答 2查看 688关注 0票数 0

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

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

模型

代码语言:javascript
复制
artist = models.ManyToManyField(ApiArtist, blank=True)

表格和验证

代码语言:javascript
复制
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。谢谢

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-10-14 08:18:52

现在,我的下面的代码正在工作。无论如何,谢谢

代码语言:javascript
复制
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
票数 1
EN

Stack Overflow用户

发布于 2012-10-13 19:00:47

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12875528

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档