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中.py文件打包成exe可执行文件详解
Mar 22 Python
Python实现对象转换为xml的方法示例
Jun 08 Python
Python之os操作方法(详解)
Jun 15 Python
Python使用cx_Freeze库生成msi格式安装文件的方法
Jul 10 Python
python 生成图形验证码的方法示例
Nov 11 Python
对python中的argv和argc使用详解
Dec 15 Python
python爬虫获取百度首页内容教学
Dec 23 Python
对python3中, print横向输出的方法详解
Jan 28 Python
Python任意字符串转16, 32, 64进制的方法
Jun 12 Python
使用python实现男神女神颜值打分系统(推荐)
Oct 31 Python
详解python opencv、scikit-image和PIL图像处理库比较
Dec 26 Python
python 从list中随机取值的方法
Nov 16 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
mysql+php分页类(已测)
2008/03/31 PHP
PHP中将字符串转化为整数(int) intval() printf() 性能测试
2020/03/20 PHP
PHP可变变量学习小结
2015/11/29 PHP
PHP与服务器文件系统的简单交互
2016/10/21 PHP
Laravel框架表单验证操作实例分析
2019/09/30 PHP
thinkphp5 + ajax 使用formdata提交数据(包括文件上传) 后台返回json完整实例
2020/03/02 PHP
textarea的value是html文件源代码,存成html文件的代码
2007/04/20 Javascript
Javascript下判断是否为闰年的Datetime包
2010/10/26 Javascript
异步加载script的代码
2011/01/12 Javascript
读jQuery之六 缓存数据功能介绍
2011/06/21 Javascript
javascript错误的认识不用关心内存管理
2012/12/15 Javascript
javascript制作的网页侧边弹出框思路及实现代码
2014/05/21 Javascript
移动端翻页插件dropload.js(支持Zepto和jQuery)
2016/07/27 Javascript
获取IE浏览器Cookie信息的方法
2017/01/23 Javascript
vue2里面ref的具体使用方法
2017/10/27 Javascript
详解vue 命名视图
2019/08/14 Javascript
[00:13]天涯墨客二技能展示
2018/08/25 DOTA
python将ip地址转换成整数的方法
2015/03/17 Python
仅用500行Python代码实现一个英文解析器的教程
2015/04/02 Python
Python EOL while scanning string literal问题解决方法
2020/09/18 Python
使用Python制作获取网站目录的图形化程序
2015/05/04 Python
Python三级目录展示的实现方法
2016/09/28 Python
selenium+python 对输入框的输入处理方法
2018/10/11 Python
opencv转换颜色空间更改图片背景
2019/08/20 Python
Python+appium框架原生代码实现App自动化测试详解
2020/03/06 Python
Python使用monkey.patch_all()解决协程阻塞问题
2020/04/15 Python
python 实现有道翻译功能
2021/02/26 Python
利用CSS3实现单选框动画特效示例代码
2016/09/26 HTML / CSS
介绍一下Java中的static关键字
2012/05/12 面试题
基督教婚礼主持词
2014/03/14 职场文书
教师爱岗敬业演讲稿
2014/05/05 职场文书
我爱我校演讲稿
2014/05/21 职场文书
南京大屠杀观后感
2015/06/02 职场文书
2019年大学生学年自我鉴定!
2019/03/25 职场文书
numpy array找出符合条件的数并赋值的示例代码
2022/06/01 Python
css如何把元素固定在容器底部的四种方式
2022/06/16 HTML / CSS