本文整理汇总了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)
示例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})
示例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(' '))
示例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)
示例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 ')
示例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), ' ')
示例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
示例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"
)
示例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)
示例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)
示例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
示例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)
示例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
示例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'})
示例15: clean
def clean(self, value):
return normpath(CharField.clean(self, value))