【问题标题】:Django - choose Choice value depending on view loadedDjango - 根据加载的视图选择选择值
【发布时间】: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


    【解决方案1】:

    假设您在视图中使用 CreateView,您可以在每个视图中覆盖 get_initial()。

    class GameAView(CreateView):
         ...
    
        def get_initial(self):
            initial = super().get_initial()
            initial['game'] = 'choice_A'
            return initial
    
    
    class GameBView(CreateView):
         ...
    
        def get_initial(self):
            initial = super().get_initial()
            initial['game'] = 'choice_B'
            return initial
    

    【讨论】:

    • 这似乎是我正在寻找的。我试图复制你的方法,但不幸的是没有成功。当我在 ChoiceField 中添加初始值时。初始应该等于什么?游戏选择?我将用我刚刚尝试过的内容更新我的问题。
    • 花了一些时间,但我找到了我的程序所需的正确上下文。你的回答很好,让我朝着正确的方向前进,谢谢。
    猜你喜欢
    • 2016-07-24
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多