本文整理匯總了Python中django.forms.Field方法的典型用法代碼示例。如果您正苦於以下問題:Python forms.Field方法的具體用法?Python forms.Field怎麽用?Python forms.Field使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.forms
的用法示例。
在下文中一共展示了forms.Field方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: render_field
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def render_field(field: Field, render_labels: bool = True) -> SafeText:
"""
Renders a form field using a custom template designed specifically for the wiki forms.
As the wiki uses custom form rendering logic, we were unable to make use of Crispy Forms for
it. This means that, in order to customize the form fields, we needed to be able to render
the fields manually. This function handles that logic.
Sometimes we don't want to render the label that goes with a field - the `render_labels`
argument defaults to True, but can be set to False if the label shouldn't be rendered.
The label rendering logic is left up to the template.
Usage: `{% render_field field_obj [render_labels=True/False] %}`
"""
unbound_field = get_unbound_field(field)
if not isinstance(render_labels, bool):
render_labels = True
template_path = TEMPLATES.get(unbound_field.__class__, TEMPLATE_PATH.format("in_place_render"))
is_markitup = isinstance(unbound_field.widget, MarkItUpWidget)
context = {"field": field, "is_markitup": is_markitup, "render_labels": render_labels}
return render(template_path, context)
示例2: _field_class_name
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def _field_class_name(cls, field_class, lookup_expr):
"""
Generate a suitable class name for the concrete field class. This is not
completely reliable, as not all field class names are of the format
<Type>Field.
ex::
BaseCSVFilter._field_class_name(DateTimeField, 'year__in')
returns 'DateTimeYearInField'
"""
# DateTimeField => DateTime
type_name = field_class.__name__
if type_name.endswith('Field'):
type_name = type_name[:-5]
# year__in => YearIn
parts = lookup_expr.split(LOOKUP_SEP)
expression_name = ''.join(p.capitalize() for p in parts)
# DateTimeYearInField
return str('%s%sField' % (type_name, expression_name))
示例3: _validate_container
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def _validate_container(self):
for field in self.model_container._meta._get_fields(reverse=False):
if isinstance(field, (AutoField,
BigAutoField,
RelatedField)):
raise ValidationError(
f'Field "{field}" of model container:"{self.model_container}" '
f'cannot be of type "{type(field)}"')
if field.attname != field.column:
raise ValidationError(
f'Field "{field}" of model container:"{self.model_container}" '
f'cannot be named as "{field.attname}", different from '
f'column name "{field.column}"')
if field.db_index:
print_warn('Embedded field index')
raise NotSupportedError(
f'This version of djongo does not support indexes on embedded fields'
)
示例4: get_entry_field
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def get_entry_field(self, questionanswer: 'QuestionAnswer' = None, student: 'Member' = None) -> forms.Field:
"""
Returns a Django Field for this question, to be filled in by the student.
If questionanswer is given, its .answer contents must be used to set the field's initial value.
If student is given, it can be used to customize the question for that student (e.g. permuting MC answers)
"""
raise NotImplementedError()
示例5: test_make_entry_field
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def test_make_entry_field(self):
for (name, field_model) in FIELD_TYPE_MODELS.items():
instance = field_model(self.standard_config)
self.assertTrue(isinstance(instance.make_entry_field(), DjangoFormsField))
示例6: __init__
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def __init__(self, max_value=None, min_value=None, choices=None, *args, **kwargs):
self.max_value, self.min_value = max_value, min_value
if choices:
forms.Field.__init__(self, widget=forms.widgets.RadioSelect(choices=choices), *args, **kwargs)
else:
forms.Field.__init__(self, *args, **kwargs)
if max_value is not None:
self.validators.append(forms.validators.MaxValueValidator(max_value))
if min_value is not None:
self.validators.append(forms.validators.MinValueValidator(min_value))
示例7: __init__
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def __init__(self, *args, **kwargs):
self.field_class = kwargs.pop('field_class', forms.Field)
super(CustomMethodFilter, self).__init__(*args, **kwargs)
示例8: obj_as_dict
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def obj_as_dict(o):
if isinstance(o, DeclarativeFieldsMetaclass):
o = FormSerializer(form=o).data
if isinstance(o, forms.Field):
o = FormFieldSerializer(field=o).data
if isinstance(o, forms.Widget):
o = FormWidgetSerializer(widget=o).data
if isinstance(o, (list, tuple)):
o = [obj_as_dict(x) for x in o]
if isinstance(o, Promise):
try:
o = force_unicode(o)
except:
# Item could be a lazy tuple or list
try:
o = [obj_as_dict(x) for x in o]
except:
raise Exception('Unable to resolve lazy object %s' % o)
if callable(o):
o = o()
if isinstance(o, dict):
for k, v in o.items():
o[k] = obj_as_dict(v)
return o
示例9: __init__
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def __init__(self, locales: List[Tuple[str, str]], field: forms.Field, attrs=None):
widgets = []
self.locales = locales
self.enabled_locales = locales
self.field = field
for code, language in self.locales:
a = copy.copy(attrs) or {}
a["lang"] = code
widgets.append(self.widget(language=language, attrs=a))
super().__init__(widgets, attrs)
示例10: validate_field_code
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def validate_field_code(self):
field_code = self.cleaned_data.get(self.PARAM_CODE) or ''
if not self.R_FIELD_CODE.match(field_code):
self.add_error('code', '''Field codes must be lowercase, should start with a latin letter and contain
only latin letters, digits, and underscores. You cannot use a field code you have already used for this
document type.''')
reserved_suffixes = ('_sug', '_txt', FIELD_CODE_ANNOTATION_SUFFIX)
# TODO: define reserved suffixes/names in field_value_tables.py? collect/autodetect?
for suffix in reserved_suffixes:
if field_code.endswith(suffix):
self.add_error('code', '''"{}" suffix is reserved.
You cannot use a field code which ends with this suffix.'''.format(suffix))
示例11: get_fieldsets
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def get_fieldsets(self, request, obj=None):
if self.is_clone_view:
fieldsets = [
(f'Clone Document Field: {obj}', {'fields': ('code', 'document_type')})
]
return fieldsets
return self.fieldsets
示例12: clean
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def clean(self):
field_ids = set()
dependencies = list()
order_values = list()
for form in self.forms:
document_field = form.cleaned_data.get('document_field')
if document_field:
field_ids.add(document_field.pk)
if document_field.depends_on_fields.count() > 0:
dependencies.append(form)
order = form.cleaned_data.get('order')
if order in order_values:
form.add_error(None, '"Order" value should be unique')
else:
order_values.append(order)
for form in dependencies:
document_field = form.cleaned_data['document_field']
missed_fields = list()
depends_on_fields = list(document_field.depends_on_fields.all())
for field in depends_on_fields:
if field.pk not in field_ids:
missed_fields.append(field.code)
if len(missed_fields) == 1:
form.add_error(None, 'Field {0} is required for {1} field'.format(missed_fields[0],
document_field.code))
elif len(missed_fields) > 1:
form.add_error(None, 'Fields {0} is required for {1} field'.format(', '.join(missed_fields),
document_field.code))
示例13: clean_code
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def clean_code(self):
field_code = self.cleaned_data['code']
# validate only new records, skip already existing ones
if not DocumentType.objects.filter(pk=self.instance.pk).exists() and not self.CODE_RE.match(field_code):
raise forms.ValidationError('''Field codes must be lowercase, should start with a latin letter and contain
only latin letters, digits, and underscores.''')
return field_code
示例14: __new__
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def __new__(mcs, name, bases, attrs):
# Collect sub-blocks declared on the current class.
# These are available on the class as `declared_blocks`
current_blocks = []
for key, value in list(attrs.items()):
if isinstance(value, Block):
current_blocks.append((key, value))
value.set_name(key)
attrs.pop(key)
current_blocks.sort(key=lambda x: x[1].creation_counter)
attrs['declared_blocks'] = collections.OrderedDict(current_blocks)
new_class = (super(DeclarativeSubBlocksMetaclass, mcs).__new__(
mcs, name, bases, attrs))
# Walk through the MRO, collecting all inherited sub-blocks, to make
# the combined `base_blocks`.
base_blocks = collections.OrderedDict()
for base in reversed(new_class.__mro__):
# Collect sub-blocks from base class.
if hasattr(base, 'declared_blocks'):
base_blocks.update(base.declared_blocks)
# Field shadowing.
for attr, value in base.__dict__.items():
if value is None and attr in base_blocks:
base_blocks.pop(attr)
new_class.base_blocks = base_blocks
return new_class
# ========================
# django.forms integration
# ========================
示例15: __init__
# 需要導入模塊: from django import forms [as 別名]
# 或者: from django.forms import Field [as 別名]
def __init__(self, *args, **kwargs):
"""
Get a hold of our custom arguments and delegate the rest to Field
"""
# base_type is unknown to Field: pop it out of kwargs and keep it ourselves
self.base_type = kwargs.pop("base_type")
# Core arguments, including 'required', are left in the kwargs and handled by parent
super().__init__(*args, **kwargs)