2012-10-13 43 views
0

可能重複:
Django 「Enter a list of values」 form error when rendering a ManyToManyField as a Textarea試圖挽救ManyToManyField

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 
+0

請包括你的錯誤的追蹤。 – jdi

+0

@jdi我剛剛得到'輸入值列表'。我沒有得到任何回溯。 – Kulbir

+0

@jdi感謝您的鏈接。 :-) – Kulbir

回答

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 
1

首先,你不應該用乾淨的方法來保存東西。

其次,您的代碼不會將textinput中的值轉換爲列表。您的if語句中有一個split,但在返回之前不會將結果設置回artist_list

+0

我也試過'return artist_list.split(',')'。但是一樣。 – Kulbir

相關問題