Python django.forms 模块,Field() 实例源码

我们从Python开源项目中,提取了以下16个代码示例,用于说明如何使用django.forms.Field()

项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
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")
项目:django-admino    作者:erdem    | 项目源码 | 文件源码
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
项目:graphene-django    作者:graphql-python    | 项目源码 | 文件源码
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
项目:graphene-django    作者:graphql-python    | 项目源码 | 文件源码
def test_should_base_field_convert_string():
    assert_conversion(forms.Field, graphene.String)
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
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)
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
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()
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
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
项目:django-i18nfield    作者:raphaelm    | 项目源码 | 文件源码
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)
项目:Kiwi    作者:kiwitcms    | 项目源码 | 文件源码
def test_type(self):
        from django.forms import Field

        self.assertTrue(isinstance(self.field, Field))
项目:maas    作者:maas    | 项目源码 | 文件源码
def __init__(self, *args, validators=None, **kwargs):
        kwargs["validators"] = [] if validators is None else validators
        super(Field, self).__init__(*args, **kwargs)
项目:maas    作者:maas    | 项目源码 | 文件源码
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)
项目:maas    作者:maas    | 项目源码 | 文件源码
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)
项目:maas    作者:maas    | 项目源码 | 文件源码
def test_form_field_is_a_plain_field(self):
        self.assertThat(
            JSONObjectField().formfield(),
            AfterPreprocessing(type, Is(forms.Field)))
项目:django-dynamic-fields    作者:yourlabs    | 项目源码 | 文件源码
def __init__(self, **fields):
        """Given a dict of fields with action lists, prepare the JSON."""
        self.rules = []

        for field, actions in fields.items():
            self.rules.append(Rule(field, actions))

        super(Field, self).__init__(
            required=False,
            widget=Widget(self),
        )
项目:django-dynamic-fields    作者:yourlabs    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        """Add a Field with the configuration."""
        super(FormMixin, self).__init__(*args, **kwargs)
        self.fields['django_dynamic_fields'] = Field(**self._ddf)
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
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 = ThemableCheckboxInput(check_test=lambda value: False)
                # Convert value to string to avoid accidental type conversion
                data = widget.render('object_ids',
                                     six.text_type(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,
                 six.text_type(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

            if (template.defaultfilters.urlize in column.filters or
                    template.defaultfilters.yesno in column.filters):
                data = widget.render(widget_name,
                                     column.get_raw_data(datum),
                                     form_field_attributes)
            else:
                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