我有使用 Django Forms.ChoiceField 的 ModelForm。将值写入数据库有效。但是当我打开 url 时,下拉列表没有将先前选择的值显示为选定值。
我尝试设置 initial=value,但效果不佳。
class GameForm(forms.ModelForm):
gameCode = forms.ChoiceField(required=False)
def __init__(self, *args, **kwargs):
obj = AllGameCodes.objects.filter(game=game)
choices = []
choices.append(('', '-----------'))
for i in obj:
choices.append((i.code,i.description))
self.fields['gameCode'].choices = choices
in views.py,
game = games.objects.get(id=1)
form = GameForm(request.POST, initial={'code':game.code}