Django custom field implements a field to store a comma-delimited string _python

Source: Internet
Author: User

Enables you to store a comma-delimited string in a field, returning a corresponding list

Copy Code code as follows:

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 () is to comparing with integer choices
      &nbs p;         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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.