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

时间:2021-03-28 16:24:51 

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


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)

标签:django,Field,python
0
投稿

猜你喜欢

  • Django框架中间件(Middleware)用法实例分析

    2021-01-04 09:27:38
  • Python求正态分布曲线下面积实例

    2021-01-28 18:20:07
  • Python实现读写INI配置文件的方法示例

    2021-03-16 08:10:08
  • Python的命令行参数实例详解

    2023-06-11 09:05:45
  • 木鸟:ASP缓存类无错版

    2008-02-20 12:53:00
  • php设计模式之装饰模式应用案例详解

    2023-11-14 13:37:20
  • 浅析CMS生成静态页面的两种方案

    2008-03-17 12:51:00
  • Python 函数装饰器详解

    2021-11-20 04:34:16
  • 设计上的小细节

    2010-06-24 21:44:00
  • pygame多种方式实现屏保操作(自动切换、鼠标切换、键盘切换)

    2022-12-08 20:39:49
  • Python学习之字符串常用方法总结

    2021-12-19 02:19:46
  • 详解Python自动化之文件自动化处理

    2022-07-24 03:50:02
  • ASP防盗链及防下载的方法

    2007-09-19 12:22:00
  • 对python使用http、https代理的实例讲解

    2022-03-13 00:03:08
  • python类参数self使用示例

    2023-05-27 17:15:18
  • python实现超市扫码仪计费

    2023-01-11 03:53:31
  • Python随机数模块详情

    2021-10-26 06:47:34
  • Python打印不合法的文件名

    2021-06-29 03:40:19
  • 利用Python实现sqlite3增删改查的封装

    2021-06-19 14:57:05
  • python Pillow图像降噪处理颜色处理

    2022-08-07 16:11:21
  • asp之家 网络编程 m.aspxhome.com