我刚从Django开始,有以下内容:
models.py:
class Song(models.Model):
name = models.CharField(max_length=200, blank=False, null=False)
artist = models.ForeignKey(Artist, blank=False, null=False)
class Artist(models.Model):
name = models.CharField(max_length=200, unique=True)现在我有了一个宋的模型形式,但目前没有能力添加不存在的艺术家(呈现为下拉)。这将是一个很好的允许用户添加艺术家的动态,但一直未能找到一个方法,使其发挥作用。我看到了很多关于复制管理员“添加另一个.”的答案。但不断遇到障碍和过时的信息。
我试过的是:
有没有一种方法可以方便地从歌曲形式中添加另一位艺术家?我不介意在艺术家选择下面呈现一个新的文本框,用户可以在这里添加一个新的艺术家,但我不知道如何使用ModelForms,然后在保存之前将艺术家添加到数据库中。
任何建议都将不胜感激!
发布于 2015-11-10 18:53:52
它将有助于了解您正在使用什么来创建您的表单。我想您使用的是ModelFrom。如果您正在使用jQuery,我认为您可以在forms.py中使用以下内容来捕捉新的艺术家。但是,如果您正在使用jQuery,我会将单个表单保存为模板,并根据新艺术家的按钮或链接事件显示它们。
forms.py
class SongForm (forms.ModelForm):
new_artist_name = forms.CharField()
class Meta:
model = Song
def save(self, commit=True):
# do something with self.cleaned_data['new_artist']
new_artist = Artists.objects.filter('new_artist_name')
if new_artist.exists():
# Save song to artist.
else:
# Create and save new artist and save song to the
# new artist.
return super(SongForm, self).save(commit=commit)https://stackoverflow.com/questions/33635830
复制相似问题