django自定義Field實(shí)現(xiàn)一個字段存儲以逗號分隔的字符串
實(shí)現(xiàn)了在一個字段存儲以逗號分隔的字符串,返回一個相應(yīng)的列表
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)
相關(guān)文章
Pytest執(zhí)行unittest TestSuite(測試套件)的實(shí)現(xiàn)方法
TestSuite一直是unittest的靈活與精髓之處,在繁多的測試用例中,可以任意挑選和組合各種用例集,這篇文章主要介紹了Pytest執(zhí)行unittest TestSuite(測試套件)的實(shí)現(xiàn)方法,需要的朋友可以參考下2021-08-08
Python使用urllib模塊的urlopen超時問題解決方法
這篇文章主要介紹了Python使用urllib模塊的urlopen超時問題解決方法,本文使用socket模塊中的setdefaulttimeout函數(shù)解決了超時問題,需要的朋友可以參考下2014-11-11
使用Python在Excel中創(chuàng)建和取消數(shù)據(jù)分組
Excel中的分組是一種通過添加層級結(jié)構(gòu)將相鄰行或列組織在一起的功能,當(dāng)分組完成后,用戶可以通過折疊或展開數(shù)據(jù)組來簡化數(shù)據(jù)視圖,這篇博客將介紹如何使用Python在Excel中創(chuàng)建或取消數(shù)據(jù)分組,需要的朋友可以參考下2025-02-02
JavaScript中的模擬事件和自定義事件實(shí)例分析
這篇文章主要介紹了JavaScript中的模擬事件和自定義事件,結(jié)合實(shí)例形式分析了JavaScript模擬事件和自定義事件相關(guān)操作步驟、實(shí)現(xiàn)技巧與注意事項(xiàng),需要的朋友可以參考下2018-07-07
python中面向?qū)ο蟮淖⒁恻c(diǎn)概述總結(jié)
大家好,本篇文章主要講的是python中面向?qū)ο蟮淖⒁恻c(diǎn)概述總結(jié),感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-02-02
Python用zip函數(shù)同時遍歷多個迭代器示例詳解
這篇文章主要給大家進(jìn)行介紹了Python如何用zip函數(shù)同時遍歷多個迭代器,文中給出了示例以及原理和注意事項(xiàng),相信會對大家的理解和學(xué)習(xí)很有幫助,有需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧。2016-11-11
pytest自動化測試數(shù)據(jù)驅(qū)動yaml/excel/csv/json
這篇文章主要為大家介紹了pytest自動化測試數(shù)據(jù)驅(qū)動yaml/excel/csv/json的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06

