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')

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

相关文章

  • python中数据爬虫requests库使用方法详解

    python中数据爬虫requests库使用方法详解

    本篇文章主要介绍了python中数据爬虫requests库使用方法详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • 利用python微信库itchat实现微信自动回复功能

    利用python微信库itchat实现微信自动回复功能

    最近发现了一个特别好玩的Python 微信库itchat,可以实现自动回复等多种功能,下面这篇文章主要给大家介绍了利用python微信库itchat实现微信自动回复功能的相关资料,需要的朋友可以参考学习,下面来一起看看吧。
    2017-05-05
  • Python批量修改文件后缀的方法

    Python批量修改文件后缀的方法

    这篇文章主要介绍了Python批量修改文件后缀的方法,有需要的朋友可以参考一下
    2014-01-01
  • Python+Selenium实现短视频热点爬取

    Python+Selenium实现短视频热点爬取

    随着短视频的大火,不仅可以给人们带来娱乐,还有热点新闻时事以及各种知识,刷短视频也逐渐成为了日常生活的一部分。本文将通过Pyhton依托Selenium来爬取短视频热点,需要的可以参考一下
    2022-04-04
  • Python中的__repr__()方法小结

    Python中的__repr__()方法小结

    在 Python 中,__repr__() 是一个特殊方法,用于定义对象的字符串表示形式,本文主要介绍了Python中的__repr__()方法小结,具有一定的参考价值,感兴趣的可以了解一下
    2024-01-01
  • TensorFlow人工智能学习创建数据实现示例详解

    TensorFlow人工智能学习创建数据实现示例详解

    这篇文章主要为大家介绍了TensorFlow人工智能学习创建数据实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2021-11-11
  • 详解Django配置JWT认证方式

    详解Django配置JWT认证方式

    这篇文章主要介绍了Django 配置JWT认证方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-05-05
  • python的内存管理和垃圾回收机制详解

    python的内存管理和垃圾回收机制详解

    这篇文章主要介绍了python内存管理和垃圾回收机制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-05-05
  • python编写计算器功能

    python编写计算器功能

    这篇文章主要为大家详细介绍了python编写计算器功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-10-10
  • Python+OpenCV图像处理之直方图统计

    Python+OpenCV图像处理之直方图统计

    直方图就是对图像的另外一种解释,它描述了整幅图像的灰度分布。通过直方图我们可以对图像的亮度、灰度分布、对比度等有了一个直观的认识。本文将为大家详细介绍一下如何通过OpenCV实现直方图统计,感兴趣的可以了解一下
    2021-12-12

最新评论