【问题标题】:How do I set up this formset in Django如何在 Django 中设置此表单集
【发布时间】:2015-03-07 20:04:34
【问题描述】:

我正在尝试构建一个用于安排单(或双)淘汰赛的表格。例如,假设一个联赛有 TeamA、TeamB、TeamC 和 TeamD(所有这些都已在我的数据库中定义)。

表单应该类似于

Style: choice field - {single or double elimination}
Seed1: choice field - {TeamA or TeamB or TeamC or TeamD}
Seed2: choice field - {TeamA or TeamB or TeamC or TeamD}
Seed3: choice field - {TeamA or TeamB or TeamC or TeamD}
Seed4: choice field - {TeamA or TeamB or TeamC or TeamD}

这就是我所拥有的……

class EliminationForm(Form):
    """
    Form for generating an elimination structure of Game instances
    """

    choices = [(1, "Single Elimination"), (2, "Double Elimination")]
    style = ChoiceField(choices=choices, widget=Select(attrs={'class':'form-control'}))

如何设置此表单来为联盟中的每支球队动态构建“种子”字段?

这是我的models.py

class League(models.Model):
    league_name = models.CharField(max_length=60)

class Team(models.Model):
    league = models.ForeignKey('League')
    team_name = models.CharField(max_length=60)

【问题讨论】:

    标签: django python-3.x django-forms


    【解决方案1】:

    我认为您正在寻找的是ModelChoiceField

    它将允许您使用数据库中的团队填充下拉列表:

    class EliminationForm(Form):
        """
        Form for generating an elimination structure of Game instances
        """
    
        choices = [(1, "Single Elimination"), (2, "Double Elimination")]
        style = ChoiceField(
            choices=choices, 
            widget=Select(attrs={'class':'form-control'})
        )
    
        seed1 = ModelChoiceField(
            queryset=Team.objects.all(),
        )
        seed2 = ModelChoiceField(
            queryset=Team.objects.all(),
        )
        seed3 = ModelChoiceField(
            queryset=Team.objects.all(),
        )
        seed4 = ModelChoiceField(
            queryset=Team.objects.all(),
        )
    

    您还可以过滤正在使用的对象以仅选择同一联赛的球队,或仅选择分配给联赛的球队等。

    您可能还想向 Team 模型添加一个 __unicode__ 函数,以定义它在下拉列表中的显示方式。

    class Team(models.Model):
        league = models.ForeignKey('League')
        team_name = models.CharField(max_length=60)
    
        def __unicode__(self):
            return self.team_name
    

    【讨论】:

    • 谢谢,这很有帮助,但不能解决我的问题。您已经创建了一个具有静态种子数 (4) 的表格,但一个联赛可以有任意数量的球队(例如 20 支球队)。换句话说,我需要“种子”字段的数量来匹配联盟中的球队数量,这几乎可以是任何东西。这就是为什么我认为我需要使用表单集。
    猜你喜欢
    • 1970-01-01
    • 2016-09-15
    • 2019-03-31
    • 2014-12-28
    • 2010-10-08
    • 2014-09-17
    • 2021-10-17
    • 2014-03-12
    • 1970-01-01
    相关资源
    最近更新 更多