我刚开始使用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)
现在我有一个Song的模型表单,但目前无法添加尚未存在的艺术家(呈现为下拉列表)。允许用户即时添加艺术家但却无法找到实现这种功能的方法会很不错。我看到很多关于复制管理员“添加另一个......”的答案,但一直遇到障碍和过时的信息。
我尝试了什么:
有没有办法轻松添加歌曲形式的另一位艺术家?我不介意在艺术家选择下面渲染一个新的文本框,用户可以在其中添加新的艺术家,但我不知道如何使用ModelForms,然后在保存之前将艺术家添加到数据库中。
非常感谢任何建议!
答案 0 :(得分:0)
查看您用于创建表单的内容会有所帮助。我假设您使用的是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)