我想用传递给它的列表的所有单个元素预填充一个表单域:
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':producers,
'label':song.label.name}
form = AddSongForm(instance=song, initial=data)
现在,它用生产者列表填充“生产者”字段,但我希望它用该列表中的每个字符串填充它。我可以在views.py中这样做吗?还是我需要在模板中设置某种循环?这是相关的模板代码:
<div class ="form-group">
{{ form.producer.label_tag }}
{% render_field form.producer class+="form-control" %}
</div>
更新 抱歉,伙计们。弄清楚了。我需要在数据字典中使用.join():
data = {'artist':song.artist.name, 'producer':", ".join(producers),
'label':song.label.name}