当前位置: 首页>>代码示例>>Python>>正文


Python forms.CharField类代码示例

本文整理汇总了Python中django.forms.CharField的典型用法代码示例。如果您正苦于以下问题:Python CharField类的具体用法?Python CharField怎么用?Python CharField使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了CharField类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, grouping=IBAN_GROUPING, *args, **kwargs):
        kwargs.setdefault('max_length', IBAN_MAX_LENGTH)
        kwargs.setdefault('min_length', IBAN_MIN_LENGTH)

        self.grouping           = grouping
        self.default_validators = [IBANValidator()]
        CharField.__init__(self, *args, **kwargs)
开发者ID:Chedi,项目名称:django-iban-field,代码行数:7,代码来源:forms.py

示例2: make_quiz_form

def make_quiz_form(quiz, select_to_radio=False):
    """
    Generates a form on the fly based on the Quiz questions
    """
    form_fields = OrderedDict()
    for question in quiz.get_questions():
        AnswerModel = question.get_answer_class()
        model_fields = fields_for_model(AnswerModel, exclude=['userprofile', 'review'])
        if AnswerModel == MultipleChoiceAnswer or AnswerModel == RatingAnswer:
            if select_to_radio or (quiz.question_widget == quiz.RADIO_WIDGET) or (question.widget == question.RADIO_WIDGET):
                model_fields = fields_for_model(
                    AnswerModel, exclude=['userprofile', 'review'], formfield_callback=multiplechoice_to_radio)
                # Begin Diry hack
                # for when radio select has for some reason not been set by fields_for_model
                # this happens for RatingAnswer objects
                # first we check if choices exist to avoid none choice fields
                if hasattr(model_fields['answer'], '_choices'):
                    # then we check if the widget is still Select
                    if isinstance(model_fields['answer'].widget, Select):
                        # we manually make it into a Radio Select field
                        model_fields['answer'].widget = RadioSelect()
                        # we remove the empty answer choice usually preset in Select Fields
                        if not model_fields['answer']._choices[0][0]:
                            model_fields['answer']._choices.pop(0)
                # End Diry hack

        answer_field = model_fields['answer']
        answer_field.required = question.required
        # answer_field.question = question ?? should this be included
        answer_field.has_image_answers = question.has_image_answers
        answer_field.widget_to_use = question.widget
        other_field = None
        if question.image:
            thumb_size = getattr(settings, 'QUESTION_LABEL_THUMBS_SIZE', "500x400")
            thumb = get_thumbnail(question.image.file, thumb_size)
            answer_field.label = format_html(
                "<img src='{thumb}' class='img-responsive question-label' alt='{qtitle}' title='{qtitle}' /><span class='question-text-latel'>{qtitle}</span>", thumb=thumb.url, qtitle=smart_str(question.title))
            if quiz.show_question_numbers:
                answer_field.label = format_html(
                    "<img src='{thumb}' class='img-responsive question-label' alt='{qtitle}' title='{qtitle}' /><span class='question-text-latel'>{qtitle}</span>", thumb=thumb.url, qtitle=smart_str("{}. {}".format(question.order, question.title)))
        else:
            this_label = question.title
            if quiz.show_question_numbers:
                this_label = "{}. {}".format(question.order, this_label)
            if question.description:
                answer_field.label = format_html("<span class='question-text-latel'>{}</span><div class='question-description'>{}</div>", smart_str(
                    this_label), mark_safe(smart_str(question.description).replace('\n', '<br />')))
            else:
                answer_field.label = smart_str(this_label)
        if question._meta.model == MultipleChoiceQuestion:
            answer_field.queryset = MultipleChoiceOption.objects.filter(question=question)
            if answer_field.queryset.filter(other=True).exists():
                other_field = CharField()
                other_field.widget.attrs['class'] = "other-field id_answer_{}".format(question.id)
                other_field.label = _("If you selected Other, please specify what you meant")
                other_field.required = False
        form_fields['answer_{}'.format(question.id)] = answer_field
        if other_field:
            form_fields['other_{}'.format(question.id)] = other_field
    return type('QuizForm', (BaseForm,), {'base_fields': form_fields})
开发者ID:moshthepitt,项目名称:answers,代码行数:60,代码来源:forms.py

示例3: test_strip_before_checking_empty

 def test_strip_before_checking_empty(self):
     """
     A whitespace-only value, ' ', is stripped to an empty string and then
     converted to the empty value, None.
     """
     f = CharField(required=False, empty_value=None)
     self.assertIsNone(f.clean(' '))
开发者ID:ArcTanSusan,项目名称:django,代码行数:7,代码来源:test_charfield.py

示例4: test_charfield_3

 def test_charfield_3(self):
     f = CharField(max_length=10, required=False)
     self.assertEqual('12345', f.clean('12345'))
     self.assertEqual('1234567890', f.clean('1234567890'))
     msg = "'Ensure this value has at most 10 characters (it has 11).'"
     with self.assertRaisesMessage(ValidationError, msg):
         f.clean('1234567890a')
     self.assertEqual(f.max_length, 10)
     self.assertIsNone(f.min_length)
开发者ID:CrazyChief,项目名称:django,代码行数:9,代码来源:test_charfield.py

示例5: test_charfield_strip

    def test_charfield_strip(self):
        """
        Values have whitespace stripped but not if strip=False.
        """
        f = CharField()
        self.assertEqual(f.clean(' 1'), '1')
        self.assertEqual(f.clean('1 '), '1')

        f = CharField(strip=False)
        self.assertEqual(f.clean(' 1'), ' 1')
        self.assertEqual(f.clean('1 '), '1 ')
开发者ID:CrazyChief,项目名称:django,代码行数:11,代码来源:test_charfield.py

示例6: test_clean_non_string

    def test_clean_non_string(self):
        """CharField.clean() calls str(value) before stripping it."""
        class StringWrapper:
            def __init__(self, v):
                self.v = v

            def __str__(self):
                return self.v

        value = StringWrapper(' ')
        f1 = CharField(required=False, empty_value=None)
        self.assertIsNone(f1.clean(value))
        f2 = CharField(strip=False)
        self.assertEqual(f2.clean(value), ' ')
开发者ID:ArcTanSusan,项目名称:django,代码行数:14,代码来源:test_charfield.py

示例7: clean

 def clean(self, value):
     cleaned_path = CharField.clean(self, value)
     if value.lower().startswith(S3_ROOT):
         cleaned_path = s3_normpath(cleaned_path)
     else:
         cleaned_path = normpath(cleaned_path)
     return cleaned_path
开发者ID:colinstonema,项目名称:hue,代码行数:7,代码来源:forms.py

示例8: clean

 def clean(self, value):
     try:
         if "".join(value.split()) == "":
             value = "UNKNOWN"
         return CharField.clean(self,value.strip())
     except:
         raise ValidationError(
             "You provided an invalid value for your subject's race"
         )
开发者ID:lucassimon994,项目名称:ClinApp,代码行数:9,代码来源:forms.py

示例9: test_charfield_1

 def test_charfield_1(self):
     f = CharField()
     self.assertEqual('1', f.clean(1))
     self.assertEqual('hello', f.clean('hello'))
     with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
         f.clean(None)
     with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
         f.clean('')
     self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3]))
     self.assertIsNone(f.max_length)
     self.assertIsNone(f.min_length)
开发者ID:CrazyChief,项目名称:django,代码行数:11,代码来源:test_charfield.py

示例10: test_charfield_5

 def test_charfield_5(self):
     f = CharField(min_length=10, required=True)
     with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
         f.clean('')
     msg = "'Ensure this value has at least 10 characters (it has 5).'"
     with self.assertRaisesMessage(ValidationError, msg):
         f.clean('12345')
     self.assertEqual('1234567890', f.clean('1234567890'))
     self.assertEqual('1234567890a', f.clean('1234567890a'))
     self.assertIsNone(f.max_length)
     self.assertEqual(f.min_length, 10)
开发者ID:CrazyChief,项目名称:django,代码行数:11,代码来源:test_charfield.py

示例11: test_using_validators_on_other_fields

    def test_using_validators_on_other_fields(self):
        dict_validator = validators.DictionaryValidator(words=["nostromo"], threshold=0.8)
        length_validator = validators.LengthValidator(min_length=2)

        p = CharField(validators=[dict_validator, length_validator])

        p.clean("aa")
        with self.assertRaises(ValidationError):
            p.clean("a")  # too short
        with self.assertRaises(ValidationError):
            p.clean("nostrilomo")  # too much like nostromo
开发者ID:glasslion,项目名称:django-passwords,代码行数:11,代码来源:test_fields.py

示例12: test_charfield_2

 def test_charfield_2(self):
     f = CharField(required=False)
     self.assertEqual('1', f.clean(1))
     self.assertEqual('hello', f.clean('hello'))
     self.assertEqual('', f.clean(None))
     self.assertEqual('', f.clean(''))
     self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3]))
     self.assertIsNone(f.max_length)
     self.assertIsNone(f.min_length)
开发者ID:CrazyChief,项目名称:django,代码行数:9,代码来源:test_charfield.py

示例13: get_ordering_field

    def get_ordering_field(self):
        """
        Fixed get_ordering_field to not depend on self.filters because we
        overwrite them when accessing self.qs.
        """
        ordering_field = super(FilterSet, self).get_ordering_field()
        if self._meta.order_by is True:
            if getattr(self, "default_order", None):
                choices = [(",".join(self.default_order),) * 2]
            else:
                choices = []
            for field in self._meta.model._meta.get_fields():  # pylint: disable=protected-access
                label = getattr(field, "verbose_name", field.name.capitalize())
                choices += [
                    (field.name, label),
                    ("-{}".format(field.name), "{} (descending)".format(label))
                ]

            def validator_factory(queryset):
                def validate_order_by(value):
                    ordered_queryset = queryset.order_by(*value.split(","))
                    compiler = ordered_queryset.query.get_compiler(using=ordered_queryset.db)
                    try:
                        compiler.get_order_by()
                    except FieldError:
                        raise ValidationError("'{}' is not a valid order".format(value))
                return validate_order_by

            ordering_field = CharField(
                label=ordering_field.label,
                required=False,
                widget=Select,
                validators=[validator_factory(self.queryset)])
            ordering_field.choices = choices
            ordering_field.widget.choices = choices
        return ordering_field
开发者ID:blaze33,项目名称:django-rest-framework-filters,代码行数:36,代码来源:filterset.py

示例14: test_charfield_widget_attrs

    def test_charfield_widget_attrs(self):
        """
        CharField.widget_attrs() always returns a dictionary (#15912).
        """
        # Return an empty dictionary if max_length is None
        f = CharField()
        self.assertEqual(f.widget_attrs(TextInput()), {})
        self.assertEqual(f.widget_attrs(Textarea()), {})

        # Otherwise, return a maxlength attribute equal to max_length
        f = CharField(max_length=10)
        self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10'})
        self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10'})
        self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10'})
开发者ID:277800076,项目名称:django,代码行数:14,代码来源:test_charfield.py

示例15: clean

 def clean(self, value):
   return normpath(CharField.clean(self, value))
开发者ID:chenyuanjin,项目名称:storm-hue,代码行数:2,代码来源:forms.py


注:本文中的django.forms.CharField类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。