我有一个预先填写了某些数据的django表单:
def edit_song(request, song_id):
"""Edit a song."""
song = Song.objects.get(id=song_id)
if request.method != 'POST':
# Initial request; pre-fill form with current song info.
producers = []
for producer in song.producer.all():
producers.append(producer.name)
data = {'artist':song.artist.name, 'producer':", ".join(producers),
'label':song.label.name}
form = AddSongForm(instance=song, initial=data)
除非“ label”对象为“ None”(由于它是可选的,所以可能),否则它会很好地工作,在这种情况下,我会收到以下错误消息:
AttributeError,位于/ great_songs / edit_song / 727 / 'NoneType'对象没有属性'name'
仅当django表单不是'NoneType'对象时,如何制作django表单预填充标签?
答案 0 :(得分:0)
如果label
不是None
,则可以“修补”字典:
data = {'artist':song.artist.name, 'producer':", ".join(producers)}
if song.label is not None:
data['label'] = song.label.name