django自定义Field实现一个字段存储以逗号分隔的字符串


Posted in Python onApril 27, 2014

实现了在一个字段存储以逗号分隔的字符串,返回一个相应的列表

from django import forms
from django.db import models
from django.utils.text import capfirst
from django.core import exceptions

class MultiSelectFormField(forms.MultipleChoiceField):
    widget = forms.CheckboxSelectMultiple
    def __init__(self, *args, **kwargs):
        self.max_choices = kwargs.pop('max_choices', 0)
        super(MultiSelectFormField, self).__init__(*args, **kwargs)
    def clean(self, value):
        if not value and self.required:
            raise forms.ValidationError(self.error_messages['required'])
        # if value and self.max_choices and len(value) > self.max_choices:
        #     raise forms.ValidationError('You must select a maximum of %s choice%s.'
        #             % (apnumber(self.max_choices), pluralize(self.max_choices)))
        return value

class MultiSelectField(models.Field):
    __metaclass__ = models.SubfieldBase
    def get_internal_type(self):
        return "CharField"
    def get_choices_default(self):
        return self.get_choices(include_blank=False)
    def _get_FIELD_display(self, field):
        value = getattr(self, field.attname)
        choicedict = dict(field.choices)
    def formfield(self, **kwargs):
        # don't call super, as that overrides default widget if it has choices
        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name),
                    'help_text': self.help_text, 'choices': self.choices}
        if self.has_default():
            defaults['initial'] = self.get_default()
        defaults.update(kwargs)
        return MultiSelectFormField(**defaults)
    def get_prep_value(self, value):
        return value
    def get_db_prep_value(self, value, connection=None, prepared=False):
        if isinstance(value, basestring):
            return value
        elif isinstance(value, list):
            return ",".join(value)
    def to_python(self, value):
        if value is not None:
            return value if isinstance(value, list) else value.split(',')
        return ''
    def contribute_to_class(self, cls, name):
        super(MultiSelectField, self).contribute_to_class(cls, name)
        if self.choices:
            func = lambda self, fieldname = name, choicedict = dict(self.choices): ",".join([choicedict.get(value, value) for value in getattr(self, fieldname)])
            setattr(cls, 'get_%s_display' % self.name, func)
    def validate(self, value, model_instance):
        arr_choices = self.get_choices_selected(self.get_choices_default())
        for opt_select in value:
            if (int(opt_select) not in arr_choices):  # the int() here is for comparing with integer choices
                raise exceptions.ValidationError(self.error_messages['invalid_choice'] % value)
        return
    def get_choices_selected(self, arr_choices=''):
        if not arr_choices:
            return False
        list = []
        for choice_selected in arr_choices:
            list.append(choice_selected[0])
        return list
    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)
Python 相关文章推荐
python 输出一个两行字符的变量
Feb 05 Python
使用Python制作获取网站目录的图形化程序
May 04 Python
不要用强制方法杀掉python线程
Feb 26 Python
python进阶_浅谈面向对象进阶
Aug 17 Python
Python+matplotlib+numpy绘制精美的条形统计图
Jan 02 Python
python如何实现一个刷网页小程序
Nov 27 Python
python实现Virginia无密钥解密
Mar 20 Python
python验证身份证信息实例代码
May 06 Python
解决在pycharm运行代码,调用CMD窗口的命令运行显示乱码问题
Aug 23 Python
Python配置文件处理的方法教程
Aug 29 Python
在ipython notebook中使用argparse方式
Apr 20 Python
python 根据列表批量下载网易云音乐的免费音乐
Dec 03 Python
python监控网卡流量并使用graphite绘图的示例
Apr 27 #Python
python抓取网页图片示例(python爬虫)
Apr 27 #Python
python实现sublime3的less编译插件示例
Apr 27 #Python
python中的实例方法、静态方法、类方法、类变量和实例变量浅析
Apr 26 #Python
Python设计模式之单例模式实例
Apr 26 #Python
Python设计模式之观察者模式实例
Apr 26 #Python
Python设计模式之代理模式实例
Apr 26 #Python
You might like
追求程序速度,而不是编程的速度
2008/04/23 PHP
php若干单维数组遍历方法的比较
2011/09/20 PHP
php中常量DIRECTORY_SEPARATOR用法深入分析
2014/11/14 PHP
学习php设计模式 php实现单例模式(singleton)
2015/12/07 PHP
PHP读取mssql json数据中文乱码的解决办法
2016/04/11 PHP
详解PHP字符串替换str_replace()函数四种用法
2017/10/13 PHP
Swoole 5将移除自动添加Event::wait()特性详解
2019/07/10 PHP
分享Javascript中最常用的55个经典小技巧
2013/11/29 Javascript
JavaScript作用域与作用域链深入解析
2013/12/06 Javascript
如何将网页表格内容导入excel
2014/02/18 Javascript
解决用jquery load加载页面到div时,不执行页面js的问题
2014/02/22 Javascript
js的for in循环和java里foreach循环的区别分析
2015/01/28 Javascript
Jquery异步提交表单代码分享
2015/03/26 Javascript
js给selected添加options的方法
2015/05/06 Javascript
js实现点击向下展开的下拉菜单效果代码
2015/09/01 Javascript
JS简单实现String转Date的方法
2016/03/02 Javascript
js实现页面a向页面b传参的方法
2016/05/29 Javascript
React Native 真机断点调试+跨域资源加载出错问题的解决方法
2018/01/18 Javascript
浅谈Vue.js组件(二)
2019/04/09 Javascript
jquery实现动态创建form并提交的方法示例
2019/05/27 jQuery
layui多iframe页面控制定时器运行的方法
2019/09/05 Javascript
vue 实现把路由单独分离出来
2020/08/13 Javascript
Pycharm学习教程(6) Pycharm作为Vim编辑器使用
2017/05/03 Python
一文秒懂python读写csv xml json文件各种骚操作
2019/07/04 Python
Python 保持登录状态进行接口测试的方法示例
2019/08/06 Python
使用Pyhton集合set()实现成果查漏的例子
2019/11/24 Python
Selenium+BeautifulSoup+json获取Script标签内的json数据
2020/12/07 Python
美国保健品专家:Life Extension
2018/05/04 全球购物
德国在线香料制造商:Gewürzland
2020/03/10 全球购物
应聘教师自荐信
2013/10/12 职场文书
电脑专业个人求职信范文
2014/02/04 职场文书
银行爱岗敬业演讲稿
2014/05/05 职场文书
综合素质评价思想道德自我评价
2015/03/09 职场文书
小学班主任教育随笔
2015/08/15 职场文书
python实现的web监控系统
2021/04/27 Python
Requests什么的通通爬不了的Python超强反爬虫方案!
2021/05/20 Python