Django 表单模型选择框如何使用分组

 更新时间:2019年05月16日 08:21:28   作者:栖迟於一丘  
这篇文章主要介绍了Django 表单模型选择框如何使用分组,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

起步

Django 表单中有两种字段类型可以使用选择框: ChoiceFieldModelChoiceField

对于 ChoiceField 的基本使用是:

class ExpenseForm(forms.Form):
  CHOICES = (
    (11, 'Credit Card'),
    (12, 'Student Loans'),
    (13, 'Taxes'),
    (21, 'Books'),
    (22, 'Games'),
    (31, 'Groceries'),
    (32, 'Restaurants'),
  )
  date = forms.DateField()
  category = forms.ChoiceField(choices=CHOICES)

它能渲染出:

使用分组下拉框

还可以使用如下方式生成 <optgourp> 标签:

class ExpenseForm(forms.Form):
  CHOICES = (
    ('Debt', (
      (11, 'Credit Card'),
      (12, 'Student Loans'),
      (13, 'Taxes'),
    )),
    ('Entertainment', (
      (21, 'Books'),
      (22, 'Games'),
    )),
    ('Everyday', (
      (31, 'Groceries'),
      (32, 'Restaurants'),
    )),
  )
  date = forms.DateField()
  category = forms.ChoiceField(choices=CHOICES)

能够渲染为:

分组模型下拉框

如果使用的是 ModelChoiceField ,那抱歉,Django本身没有提供解决方案。

https://code.djangoproject.com/ticket/27331 中提供了一个很好的解决方案。

首先为需要分类的类型创建模型,在另一个模型中用外键关联它:

from django.db import models

class Category(models.Model):
  name = models.CharField(max_length=30)
  parent = models.ForeignKey('Category', on_delete=models.CASCADE, null=True)

  def __str__(self):
    return self.name

class Expense(models.Model):
  amount = models.DecimalField(max_digits=10, decimal_places=2)
  date = models.DateField()
  category = models.ForeignKey(Category, on_delete=models.CASCADE)

  def __str__(self):
    return self.amount

其次,创建一个新的表单 Field 类型:

from functools import partial
from itertools import groupby
from operator import attrgetter

from django.forms.models import ModelChoiceIterator, ModelChoiceField

class GroupedModelChoiceIterator(ModelChoiceIterator):
  def __init__(self, field, groupby):
    self.groupby = groupby
    super().__init__(field)

  def __iter__(self):
    if self.field.empty_label is not None:
      yield ("", self.field.empty_label)
    queryset = self.queryset
    # Can't use iterator() when queryset uses prefetch_related()
    if not queryset._prefetch_related_lookups:
      queryset = queryset.iterator()
    for group, objs in groupby(queryset, self.groupby):
      yield (group, [self.choice(obj) for obj in objs])

class GroupedModelChoiceField(ModelChoiceField):
  def __init__(self, *args, choices_groupby, **kwargs):
    if isinstance(choices_groupby, str):
      choices_groupby = attrgetter(choices_groupby)
    elif not callable(choices_groupby):
      raise TypeError('choices_groupby must either be a str or a callable accepting a single argument')
    self.iterator = partial(GroupedModelChoiceIterator, groupby=choices_groupby)
    super().__init__(*args, **kwargs)

最后,在表单中可以如下进行使用:

from django import forms
from .fields import GroupedModelChoiceField
from .models import Category, Expense

class ExpenseForm(forms.ModelForm):
  category = GroupedModelChoiceField(
    queryset=Category.objects.exclude(parent=None), 
    choices_groupby='parent'
  )

  class Meta:
    model = Expense
    fields = ('amount', 'date', 'category')

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • pandas中merge()函数的用法解读

    pandas中merge()函数的用法解读

    这篇文章主要介绍了pandas中merge()函数的用法解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • Python聊天室程序(基础版)

    Python聊天室程序(基础版)

    这篇文章主要为大家详细介绍了Python聊天室程序的基础版,包含客户端和服务器端两部分,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-04-04
  • Django {{ MEDIA_URL }}无法显示图片的解决方式

    Django {{ MEDIA_URL }}无法显示图片的解决方式

    这篇文章主要介绍了Django {{ MEDIA_URL }}无法显示图片的解决方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • Python读取YAML文件过程详解

    Python读取YAML文件过程详解

    这篇文章主要介绍了Python读取YAML文件过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • python实现希尔密码加密的示例代码

    python实现希尔密码加密的示例代码

    本文主要介绍了python实现希尔密码加密,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-08-08
  • python 随机数使用方法,推导以及字符串,双色球小程序实例

    python 随机数使用方法,推导以及字符串,双色球小程序实例

    下面小编就为大家带来一篇python 随机数使用方法,推导以及字符串,双色球小程序实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • python人工智能tensorflow函数tf.get_collection使用方法

    python人工智能tensorflow函数tf.get_collection使用方法

    这篇文章主要为大家介绍了python人工智能tensorflow函数tf.get_collection使用方法,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • Python线程池thread pool创建使用及实例代码分享

    Python线程池thread pool创建使用及实例代码分享

    这篇文章主要介绍了Python线程池(thread pool)创建使用及实例代码分享,文章围绕主题展开详细的内容介绍具有一定的参考价值,需要的小伙伴可以参考一下
    2022-06-06
  • Python进阶学习之特殊方法实例详析

    Python进阶学习之特殊方法实例详析

    一般说来,特殊的方法都被用来模仿某个行为。下面这篇文章主要给大家介绍了关于Python进阶学习之特殊方法的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起看看吧。
    2017-12-12
  • python获取系统内存占用信息的实例方法

    python获取系统内存占用信息的实例方法

    在本篇文章里小编给大家整理的是关于python获取系统内存占用信息的实例方法,有需要的朋友们可以参考学习下。
    2020-07-07

最新评论