仅当对象不是'None'时才预填Django表单

时间:2019-01-05 18:12:57

标签: django python-3.x forms

我有一个预先填写了某些数据的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表单预填充标签?

1 个答案:

答案 0 :(得分:0)

如果label不是None,则可以“修补”字典:

data = {'artist':song.artist.name, 'producer':", ".join(producers)}
if song.label is not None:
    data['label'] = song.label.name