Python django.forms.Field() Examples

The following are 30 code examples for showing how to use django.forms.Field(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms , or try the search function .

Example 1
Project: site   Author: python-discord   File: wiki_extra.py    License: MIT License 6 votes vote down vote up
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
Project: Dailyfresh-B2C   Author: BeanWei   File: filters.py    License: Apache License 2.0 6 votes vote down vote up
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
Project: djongo   Author: nesdis   File: fields.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 5
Project: coursys   Author: sfu-fas   File: tests.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 6
Project: coursys   Author: sfu-fas   File: fields.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 7
Project: anytask   Author: znick   File: model_user_profile_filter.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.field_class = kwargs.pop('field_class', forms.Field)

        super(CustomMethodFilter, self).__init__(*args, **kwargs) 
Example 8
Project: django-admino   Author: erdem   File: serializers.py    License: MIT License 5 votes vote down vote up
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 9
Project: pycon   Author: pythonitalia   File: forms.py    License: MIT License 5 votes vote down vote up
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 10
Project: lexpredict-contraxsuite   Author: LexPredict   File: admin.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 11
Project: lexpredict-contraxsuite   Author: LexPredict   File: admin.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 12
Project: lexpredict-contraxsuite   Author: LexPredict   File: admin.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 13
Project: lexpredict-contraxsuite   Author: LexPredict   File: admin.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 14
Project: lexpredict-contraxsuite   Author: LexPredict   File: admin.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 15
Project: wagtail   Author: wagtail   File: base.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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
# ======================== 
Example 16
Project: richie   Author: openfun   File: array.py    License: MIT License 5 votes vote down vote up
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) 
Example 17
Project: site   Author: python-discord   File: wiki_extra.py    License: MIT License 5 votes vote down vote up
def get_unbound_field(field: Union[BoundField, Field]) -> Field:
    """
    Unwraps a bound Django Forms field, returning the unbound field.

    Bound fields often don't give you the same level of access to the field's underlying attributes,
    so sometimes it helps to have access to the underlying field object.
    """
    while isinstance(field, BoundField):
        field = field.field

    return field 
Example 18
Project: graphene-django   Author: graphql-python   File: test_converter.py    License: MIT License 5 votes vote down vote up
def assert_conversion(django_field, graphene_field, *args):
    field = django_field(*args, help_text="Custom Help Text")
    graphene_type = convert_form_field(field)
    assert isinstance(graphene_type, graphene_field)
    field = graphene_type.Field()
    assert field.description == "Custom Help Text"
    return field 
Example 19
Project: graphene-django   Author: graphql-python   File: test_converter.py    License: MIT License 5 votes vote down vote up
def test_should_base_field_convert_string():
    assert_conversion(forms.Field, String) 
Example 20
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: djangoforms.py    License: Apache License 2.0 5 votes vote down vote up
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 21
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: djangoforms.py    License: Apache License 2.0 5 votes vote down vote up
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 22
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: djangoforms.py    License: Apache License 2.0 5 votes vote down vote up
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 23
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 24
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 25
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_disabled_field_has_changed_always_false(self):
        disabled_field = Field(disabled=True)
        self.assertFalse(disabled_field.has_changed('x', 'y')) 
Example 26
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 27
Project: djongo   Author: nesdis   File: test_base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_disabled_field_has_changed_always_false(self):
        disabled_field = Field(disabled=True)
        self.assertFalse(disabled_field.has_changed('x', 'y')) 
Example 28
Project: avos   Author: CiscoSystems   File: base.py    License: Apache License 2.0 5 votes vote down vote up
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 29
Project: avos   Author: CiscoSystems   File: base.py    License: Apache License 2.0 5 votes vote down vote up
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 30
Project: maas   Author: maas   File: fields.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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)