【发布时间】:2020-04-06 14:00:53
【问题描述】:
我有一个 (forms.form) 类,我可以在其中选择。我希望在我加载view_1 时决定该视图的选择是choice_A,然后当我加载view_2 时,该视图的选择是choice_B。因此,根据加载的视图,选择值会相应变化。
CreateGameForm(forms.form) 类
class CreateGame(forms.Form):
game_choices = ([
('choice_A', 'choice_A'),
('choice_B', 'choice_B')
])
game = forms.ChoiceField(choices=game_choices , required=True)
我试图通过在游戏中添加一个来更改初始值,然后在 def init 中将它与一个在视图/URL_pattern 时更改初始值的函数一起添加变化,但运气不佳。
有什么想法吗?
使用初始方法
class CreateGame(forms.Form):
game_choices = ([
('choice_A', 'choice_A'),
('choice_B', 'choice_B')
])
game = forms.ChoiceField(choices=game_choices , required=True, initial="choice_A")
我的 createView
class CreateGameA(CreateView):
template_name = 'otree/gameA.html'
url_pattern = r"^create_game/gameA/"
def get_initial(self):
initial = super().get_initial()
initial['game'] = 'gameA'
return initial
编辑
确保有FormMixin或者使用CreateView,否则不能使用get_initial。
【问题讨论】:
标签: django django-models django-forms django-views