使用optgroups

时间:2015-07-08 08:26:16

标签: python django django-models django-forms django-crispy-forms

我有以下django模型:

class BaseModel(models.Model):
    uuid = UUIDField()
    created = models.DateTimeField(auto_now_add=True, null=True)
    modified = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        abstract = True

class Company(BaseModel):
    title = models.CharField(_(u'Title'), max_length=128)

class Profile(BaseModel):
    company = models.ForeignKey(Company, verbose_name='Company')
    user = models.OneToOneField(User, verbose_name='User', null=True, blank=True)

class ServiceCategory(BaseModel):
    company = models.ForeignKey(Company)
    title = models.CharField(_(u'Title'), max_length=64)

class Service(BaseModel):
    category = models.ForeignKey(ServiceCategory)
    title = models.CharField(_(u'Title'), max_length=64)

如您所见,每个ServiceCategory都有Company外键。公司还用于对用户进行分组(每个用户与个人资料有一个关系,其中公司是个人资料的外键。

无论如何,我需要一个带有下拉列表的表单字段,它将按类别显示公司中所有可用的服务(使用optgroup)(类别不可选),例如:

组别

  • 服务1
  • 服务2
  • 服务3

类别2

  • 服务4
  • 服务5

有任何建议如何实现这一目标?

1 个答案:

答案 0 :(得分:-2)

DJ表单支持optgroup,但您需要为表单字段提供自定义格式化选项列表。

# in the form init
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

    # you need to manual format for queryset to be in this format
    service_choices = (
     ('Cat1', (
       ('service1_id', 'Service1'),
       ('service2_id', 'Service2'),
     ),
     ('Cat2', (
       ('service3_id', 'Service3'),
       ('service4_id', 'Service4'),
     ),
    )

self.fields['your_service_field'].choices = service_choices