django表单提交到数据库(Django 表单模型选择框如何使用分组)
类别:脚本大全 浏览量:2021
时间:2021-10-02 01:43:59 django表单提交到数据库
Django 表单模型选择框如何使用分组起步
django 表单中有两种字段类型可以使用选择框: choicefield
和 modelchoicefield
。
对于 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' ) |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持开心学习网。
原文链接:http://www.hongweipeng.com/index.php/archives/1790/
您可能感兴趣
- django测试服务器静态资源放哪里(Django使用redis缓存服务器的实现代码示例)
- django怎么创建模板文件(django模板结构优化的方法)
- django参数判断(Django保护敏感信息的方法示例)
- django响应返回的常用方法(Django异步任务之Celery的基本使用)
- django模板自定义(详解Django项目中模板标签及模板的继承与引用网站中快速布置广告)
- python 后台django(Python Django给admin添加Action的方法实例详解)
- django 如何实现高并发(Django如何防止定时任务并发浅析)
- django mysql设置(Django框架使用mysql视图操作示例)
- django admin 开发实例(Django给admin添加Action的步骤详解)
- django框架全面讲解(Django uwsgi Nginx 的生产环境部署详解)
- django数据库详解(Django页面数据的缓存与使用的具体方法)
- pycharm怎么创建django项目(Python、 Pycharm、Django安装详细教程图文)
- django部署(Django 中间键和上下文处理器的使用)
- django用户上传文件怎么接收(Django框架文件上传与自定义图片上传路径、上传文件名操作分析)
- django参数配置(详解重置Django migration的常见方式)
- django连接mysql不支持中文插入(Django创建项目+连通mysql的操作方法)
- 2019年外媒秋季新番动画角色CP排行榜,桐人和爱丽丝落榜(2019年外媒秋季新番动画角色CP排行榜)
- 新一小兰领衔 盘点动漫中的那些 远距离恋爱情侣(盘点动漫中的那些)
- 大事件 合肥四中火了(大事件合肥四中火了)
- 翼龙贷组织出借人调研 感受鄱阳 借 来的致富路(翼龙贷组织出借人调研)
- 2023新国风戏曲教育寒假集训班汇报演出《戏娃闹元宵》图文报道(2023新国风戏曲教育寒假集训班汇报演出戏娃闹元宵图文报道)
- 九儿《狐踪谍影》出演热血女特警,戏份杀青受关注(九儿狐踪谍影出演热血女特警)
热门推荐
- 如何判断数据是json还是字符串(JSON.stringify的多种用法总结)
- 服务器怎么创建网站(网站如何选择服务器空间?)
- python字符串匹配教程(Python字符串匹配之6种方法的使用详解)
- laravel框架如何查询空的信息(使用Laravel中的查询构造器实现增删改查功能)
- web前端怎么设置容器(Web应用中设置Context Path案例详解)
- dedecms无缩略图怎么设置(DEDECMS转移data目录后 验证码不显示解决办法)
- ubuntu设置用户免密码(Ubuntu修改密码及密码复杂度策略设置方法)
- redis新增数据分页(Scrapy-Redis结合POST请求获取数据的方法示例)
- mysql删除的delete怎么找回(MySQL Delete 删数据后磁盘空间未释放的原因)
- html5 postMessage(html5关于外链嵌入页面通信问题postMessage解决跨域通信)
排行榜
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9