Python django.forms.Field() Examples
The following are 30
code examples of django.forms.Field().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.forms
, or try the search function
.
Example #1
Source File: wiki_extra.py From site with MIT License | 6 votes |
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)
Example #2
Source File: filters.py From Dailyfresh-B2C with Apache License 2.0 | 6 votes |
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))
Example #3
Source File: fields.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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' )
Example #4
Source File: test_base.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_field_sets_widget_is_required(self): self.assertTrue(Field(required=True).widget.is_required) self.assertFalse(Field(required=False).widget.is_required)
Example #5
Source File: djangoforms.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def __init__(self, reference_class, query=None, choices=None, empty_label=u'---------', required=True, widget=forms.Select, label=None, initial=None, help_text=None, *args, **kwargs): """Constructor. Args: reference_class: required; the db.Model subclass used in the reference query: optional db.Query; default db.Query(reference_class) choices: optional explicit list of (value, label) pairs representing available choices; defaults to dynamically iterating over the query argument (or its default) empty_label: label to be used for the default selection item in the widget; this is prepended to the choices required, widget, label, initial, help_text, *args, **kwargs: like for forms.Field.__init__(); widget defaults to forms.Select """ assert issubclass(reference_class, db.Model) if query is None: query = db.Query(reference_class) assert isinstance(query, db.Query) super(ModelChoiceField, self).__init__(required, widget, label, initial, help_text, *args, **kwargs) self.empty_label = empty_label self.reference_class = reference_class self._query = query self._choices = choices self._update_widget_choices()
Example #6
Source File: djangoforms.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def clean(self, value): """Override Field.clean() to do reference-specific value cleaning. This turns a non-empty value into a model instance. """ value = super(ModelChoiceField, self).clean(value) if not value: return None instance = db.get(value) if instance is None: raise db.BadValueError(self.error_messages['invalid_choice']) return instance
Example #7
Source File: test_base.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_field_sets_widget_is_required(self): self.assertTrue(Field(required=True).widget.is_required) self.assertFalse(Field(required=False).widget.is_required)
Example #8
Source File: test_base.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_cooperative_multiple_inheritance(self): class A: def __init__(self): self.class_a_var = True super().__init__() class ComplexField(Field, A): def __init__(self): super().__init__() f = ComplexField() self.assertTrue(f.class_a_var)
Example #9
Source File: test_base.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_disabled_field_has_changed_always_false(self): disabled_field = Field(disabled=True) self.assertFalse(disabled_field.has_changed('x', 'y'))
Example #10
Source File: djangoforms.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def get_form_field(self, form_class=forms.CharField, **kwargs): """Return a Django form field appropriate for this property. Args: form_class: a forms.Field subclass, default forms.CharField Additional keyword arguments are passed to the form_class constructor, with certain defaults: required: self.required label: prettified self.verbose_name, if not None widget: a forms.Select instance if self.choices is non-empty initial: self.default, if not None Returns: A fully configured instance of form_class, or None if no form field should be generated for this property. """ defaults = {'required': self.required} if self.verbose_name: defaults['label'] = self.verbose_name.capitalize().replace('_', ' ') if self.choices: choices = [] if not self.required or (self.default is None and 'initial' not in kwargs): choices.append(('', '---------')) for choice in self.choices: choices.append((str(choice), unicode(choice))) defaults['widget'] = forms.Select(choices=choices) if self.default is not None: defaults['initial'] = self.default defaults.update(kwargs) return form_class(**defaults)
Example #11
Source File: test_base.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_disabled_field_has_changed_always_false(self): disabled_field = Field(disabled=True) self.assertFalse(disabled_field.has_changed('x', 'y'))
Example #12
Source File: base.py From avos with Apache License 2.0 | 5 votes |
def get_data(self, datum, column, row): """Fetches the data to be displayed in this cell.""" table = row.table if column.auto == "multi_select": data = "" if row.can_be_selected(datum): widget = forms.CheckboxInput(check_test=lambda value: False) # Convert value to string to avoid accidental type conversion data = widget.render('object_ids', unicode(table.get_object_id(datum)), {'class': 'table-row-multi-select'}) table._data_cache[column][table.get_object_id(datum)] = data elif column.auto == "form_field": widget = column.form_field if issubclass(widget.__class__, forms.Field): widget = widget.widget widget_name = "%s__%s" % \ (column.name, unicode(table.get_object_id(datum))) # Create local copy of attributes, so it don't change column # class form_field_attributes form_field_attributes = {} form_field_attributes.update(column.form_field_attributes) # Adding id of the input so it pairs with label correctly form_field_attributes['id'] = widget_name data = widget.render(widget_name, column.get_data(datum), form_field_attributes) table._data_cache[column][table.get_object_id(datum)] = data elif column.auto == "actions": data = table.render_row_actions(datum, pull_right=False) table._data_cache[column][table.get_object_id(datum)] = data else: data = column.get_data(datum) if column.cell_attributes_getter: cell_attributes = column.cell_attributes_getter(data) or {} self.attrs.update(cell_attributes) return data
Example #13
Source File: base.py From avos with Apache License 2.0 | 5 votes |
def inline_update_action(self, request, datum, cell, obj_id, cell_name): """Handling update by POST of the cell. """ new_cell_value = request.POST.get( cell_name + '__' + obj_id, None) if issubclass(cell.column.form_field.__class__, forms.Field): try: # using Django Form Field to parse the # right value from POST and to validate it new_cell_value = ( cell.column.form_field.clean( new_cell_value)) cell.update_action.action( self.request, datum, obj_id, cell_name, new_cell_value) response = { 'status': 'updated', 'message': '' } return HttpResponse( json.dumps(response), status=200, content_type="application/json") except core_exceptions.ValidationError: # if there is a validation error, I will # return the message to the client exc_type, exc_value, exc_traceback = ( sys.exc_info()) response = { 'status': 'validation_error', 'message': ' '.join(exc_value.messages)} return HttpResponse( json.dumps(response), status=400, content_type="application/json")
Example #14
Source File: fields.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def formfield(self, form_class=None, **kwargs): """Return a plain `forms.Field` here to avoid "helpful" conversions. Django's base model field defaults to returning a `CharField`, which means that anything that's not character data gets smooshed to text by `CharField.to_pytnon` in forms (via the woefully named `smart_text`). This is not helpful. """ if form_class is None: form_class = forms.Field return super().formfield(form_class=form_class, **kwargs)
Example #15
Source File: fields.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def deconstruct(self): # Override deconstruct not to fail on the removal of the 'editable' # field: the Django migration module assumes the field has its default # value (False). return Field.deconstruct(self)
Example #16
Source File: test_fields.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def test_form_field_is_a_plain_field(self): self.assertThat( JSONObjectField().formfield(), AfterPreprocessing(type, Is(forms.Field)), )
Example #17
Source File: forms.py From django-i18nfield with Apache License 2.0 | 5 votes |
def __init__(self, locales: List[str], field: forms.Field, attrs=None): widgets = [] self.locales = locales self.enabled_locales = locales self.field = field for lng in self.locales: a = copy.copy(attrs) or {} a['lang'] = lng widgets.append(self.widget(attrs=a)) super().__init__(widgets, attrs)
Example #18
Source File: filters.py From caluma with GNU General Public License v3.0 | 5 votes |
def generate_list_filter_class(inner_type): """ Return a Filter class that will resolve into a List(`inner_type`) graphene type. This allows us to do things like use `__in` and `__overlap` filters that accept graphene lists instead of a comma delimited value string that's interpolated into a list by django_filters.BaseCSVFilter (which is used to define django_filters.BaseInFilter) """ form_field = type(f"List{inner_type.__name__}FormField", (forms.Field,), {}) filter_class = type( f"{inner_type.__name__}ListFilter", (Filter,), { "field_class": form_field, "__doc__": ( f"{inner_type.__name__}ListFilter is a small extension of a raw " f"django_filters.Filter that allows us to express graphql " f"List({inner_type.__name__}) arguments using FilterSets. " f"Note that the given values are passed directly into queryset filters." ), }, ) convert_form_field.register(form_field)( lambda x: graphene.List(inner_type, required=x.required) ) return filter_class
Example #19
Source File: admin.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 5 votes |
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))
Example #20
Source File: tests.py From coursys with GNU General Public License v3.0 | 5 votes |
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))
Example #21
Source File: fields.py From coursys with GNU General Public License v3.0 | 5 votes |
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))
Example #22
Source File: model_user_profile_filter.py From anytask with MIT License | 5 votes |
def __init__(self, *args, **kwargs): self.field_class = kwargs.pop('field_class', forms.Field) super(CustomMethodFilter, self).__init__(*args, **kwargs)
Example #23
Source File: serializers.py From django-admino with MIT License | 5 votes |
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
Example #24
Source File: forms.py From pycon with MIT License | 5 votes |
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)
Example #25
Source File: admin.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 5 votes |
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))
Example #26
Source File: admin.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 5 votes |
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
Example #27
Source File: base.py From coursys with GNU General Public License v3.0 | 5 votes |
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()
Example #28
Source File: admin.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 5 votes |
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
Example #29
Source File: admin.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 5 votes |
def clean_code(self): code = self.cleaned_data['code'] if code: if not self.R_FIELD_CODE.match(code): self.add_error('code', '''Document Field Family codes must be lowercase, should start with a latin letter and contain only latin letters, digits, and underscores.''') if DocumentFieldFamily.objects.exclude(pk=self.instance.pk).filter(code__iexact=code): self.add_error('code', 'Document Field Family with the same code already exists.') return code
Example #30
Source File: base.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 # ========================