Python django.forms.IntegerField() Examples

The following are 30 code examples of django.forms.IntegerField(). 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: forms.py    From registrasion with Apache License 2.0 11 votes vote down vote up
def staff_products_form_factory(user):
    ''' Creates a StaffProductsForm that restricts the available products to
    those that are available to a user. '''

    products = inventory.Product.objects.all()
    products = ProductController.available_products(user, products=products)

    product_ids = [product.id for product in products]
    product_set = inventory.Product.objects.filter(id__in=product_ids)

    class StaffProductsForm(forms.Form):
        ''' Form for allowing staff to add an item to a user's cart. '''

        product = forms.ModelChoiceField(
            widget=forms.Select,
            queryset=product_set,
        )

        quantity = forms.IntegerField(
            min_value=0,
        )

    return StaffProductsForm 
Example #2
Source File: forms.py    From registrasion with Apache License 2.0 7 votes vote down vote up
def set_fields(cls, category, products):
        choices = []

        if not category.required:
            choices.append((0, "---"))

        for product in products:
            choice_text = "%s -- $%d each" % (product.name, product.price)
            choices.append((product.id, choice_text))

        cls.base_fields[cls.CHOICE_FIELD] = forms.TypedChoiceField(
            label=category.name,
            widget=forms.Select,
            choices=choices,
            initial=0,
            empty_value=0,
            coerce=int,
        )

        cls.base_fields[cls.QUANTITY_FIELD] = forms.IntegerField(
            label="Quantity",  # TODO: internationalise
            min_value=0,
            max_value=500,  # Issue #19. We should figure out real limit.
        ) 
Example #3
Source File: set.py    From helfertool with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')

        super(GiftSetForm, self).__init__(*args, **kwargs)

        available_gifts = Gift.objects.filter(event=self.event)
        self.gift_form_ids = {}

        for gift in available_gifts:
            id = "gift_{}".format(gift.pk)
            self.gift_form_ids[gift.pk] = id

            number = 0
            if self.instance:
                number = self.instance.get_gift_num(gift)

            self.fields[id] = forms.IntegerField(label=gift.name,
                                                 required=False,
                                                 min_value=0,
                                                 initial=number) 
Example #4
Source File: forms.py    From registrasion with Apache License 2.0 6 votes vote down vote up
def set_fields(cls, category, products):
        for product in products:
            if product.description:
                help_text = "$%d each -- %s" % (
                    product.price,
                    product.description,
                )
            else:
                help_text = "$%d each" % product.price

            field = forms.IntegerField(
                label=product.name,
                help_text=help_text,
                min_value=0,
                max_value=500,  # Issue #19. We should figure out real limit.
            )
            cls.base_fields[cls.field_name(product)] = field 
Example #5
Source File: admin.py    From django-seo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_modelinstance_form(metadata_class):
    model_class = metadata_class._meta.get_model('modelinstance')

    # Restrict content type choices to the models set in seo_models
    content_types = get_seo_content_types(metadata_class._meta.seo_models)

    # Get a list of fields, with _content_type at the start
    important_fields = ['_content_type'] + ['_object_id'] + core_choice_fields(metadata_class)
    _fields = important_fields + list(fields_for_model(model_class,
                                                  exclude=important_fields).keys())

    class ModelMetadataForm(forms.ModelForm):
        _content_type = forms.ModelChoiceField(
            queryset=ContentType.objects.filter(id__in=content_types),
            empty_label=None,
            label=capfirst(_("model")),
        )

        _object_id = forms.IntegerField(label=capfirst(_("ID")))

        class Meta:
            model = model_class
            fields = _fields

    return ModelMetadataForm 
Example #6
Source File: test_mutations.py    From pycon with MIT License 6 votes vote down vote up
def test_form_mutation_transform_is_not_required():
    class TestForm(Form):
        a = IntegerField()

        def save(self, *args, **kwargs):
            return "hello"

    class TestMutation(FormMutation):
        class Meta:
            form_class = TestForm

    @strawberry.input
    class TestInput:
        a: int

    assert TestMutation.Mutation(None, TestInput(a=1)) == "hello" 
Example #7
Source File: __init__.py    From python with Apache License 2.0 6 votes vote down vote up
def validators(self):
        # These validators can't be added at field initialization time since
        # they're based on values retrieved from `connection`.
        validators_ = super(IntegerField, self).validators
        internal_type = self.get_internal_type()
        min_value, max_value = connection.ops.integer_field_range(internal_type)
        if min_value is not None:
            for validator in validators_:
                if isinstance(validator, validators.MinValueValidator) and validator.limit_value >= min_value:
                    break
            else:
                validators_.append(validators.MinValueValidator(min_value))
        if max_value is not None:
            for validator in validators_:
                if isinstance(validator, validators.MaxValueValidator) and validator.limit_value <= max_value:
                    break
            else:
                validators_.append(validators.MaxValueValidator(max_value))
        return validators_ 
Example #8
Source File: test_mutations.py    From pycon with MIT License 6 votes vote down vote up
def test_form_mutation_response_can_be_converted_using_transform_method():
    class TestForm(Form):
        a = IntegerField()

        def save(self, *args, **kwargs):
            return "hello"

    class TestMutation(FormMutation):
        @classmethod
        def transform(cls, result):
            return "world"

        class Meta:
            form_class = TestForm

    @strawberry.input
    class TestInput:
        a: int

    assert TestMutation.Mutation(None, TestInput(a=1)) == "world" 
Example #9
Source File: test_mutations.py    From pycon with MIT License 6 votes vote down vote up
def test_form_mutation_without_context():
    class TestForm(Form):
        a = IntegerField()

        def save(self, *args, **kwargs):
            return "hello"

    class TestMutation(FormMutation):
        class Meta:
            form_class = TestForm

    @strawberry.input
    class TestInput:
        a: int

    assert TestMutation.Mutation(None, TestInput(a=1)) == "hello" 
Example #10
Source File: __init__.py    From python2017 with MIT License 6 votes vote down vote up
def validators(self):
        # These validators can't be added at field initialization time since
        # they're based on values retrieved from `connection`.
        validators_ = super(IntegerField, self).validators
        internal_type = self.get_internal_type()
        min_value, max_value = connection.ops.integer_field_range(internal_type)
        if min_value is not None:
            for validator in validators_:
                if isinstance(validator, validators.MinValueValidator) and validator.limit_value >= min_value:
                    break
            else:
                validators_.append(validators.MinValueValidator(min_value))
        if max_value is not None:
            for validator in validators_:
                if isinstance(validator, validators.MaxValueValidator) and validator.limit_value <= max_value:
                    break
            else:
                validators_.append(validators.MaxValueValidator(max_value))
        return validators_ 
Example #11
Source File: forms_json.py    From starthinker with Apache License 2.0 6 votes vote down vote up
def get_field_kind(field):
  if field['kind'] == 'string':
    return forms.CharField(max_length=255, required=False)
  elif field['kind'] == 'email':
    return forms.EmailField(max_length=255, required=False)
  elif field['kind'] == 'integer':
    return forms.IntegerField(required=False)
  elif field['kind'] == 'boolean':
    return forms.BooleanField(required=False)
  elif field['kind'] == 'text':
    return forms.CharField(widget=forms.Textarea(), required=False)
  elif field['kind'] == 'choice':
    return forms.ChoiceField(choices=map(lambda c: (c,c), field['choices']))
  elif field['kind'] == 'timezones':
    return TimezoneField()
  elif field['kind'] == 'authentication':
    return SwitchField('user', 'service', required=True)
  elif field['kind'] == 'json':
    return JsonField(required=False)
  elif field['kind'] == 'integer_list':
    return CommaSeparatedIntegerField(required=False)
  elif field['kind'] == 'string_list':
    return CommaSeparatedCharField(required=False)
  else:
    return forms.CharField(max_length=255, required=False) 
Example #12
Source File: test_forms.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_to_python_no_double_commas(self):
        field = SimpleListField(forms.IntegerField())
        with pytest.raises(exceptions.ValidationError) as excinfo:
            field.clean("1,,2")
        assert excinfo.value.messages[0] == "No leading, trailing, or double commas." 
Example #13
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {'form_class': forms.IntegerField}
        defaults.update(kwargs)
        return super(IntegerField, self).formfield(**defaults) 
Example #14
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def rel_db_type(self, connection):
        """
        Return the data type that a related field pointing to this field should
        use. In most cases, a foreign key pointing to a positive integer
        primary key will have an integer column data type but some databases
        (e.g. MySQL) have an unsigned integer type. In that case
        (related_fields_match_type=True), the primary key should return its
        db_type.
        """
        if connection.features.related_fields_match_type:
            return self.db_type(connection)
        else:
            return IntegerField().db_type(connection=connection) 
Example #15
Source File: views.py    From mirandum with Apache License 2.0 5 votes vote down vote up
def creds_form():
    class CredsForm(forms.Form):
        profile_id = forms.IntegerField()
    return CredsForm 
Example #16
Source File: test_converter.py    From graphene-django with MIT License 5 votes vote down vote up
def test_should_integer_convert_int():
    assert_conversion(forms.IntegerField, Int) 
Example #17
Source File: djangoforms.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def get_form_field(self, **kwargs):
    """Return a Django form field appropriate for an integer property.

    This defaults to an IntegerField instance.
    """
    defaults = {'form_class': forms.IntegerField}
    defaults.update(kwargs)
    return super(IntegerProperty, self).get_form_field(**defaults) 
Example #18
Source File: plugin.py    From ontask_b with MIT License 5 votes vote down vote up
def _create_datatype_field(p_type, p_help, lbl):
        """Create a new field depending on the datatype."""
        if p_type == 'integer':
            new_field = forms.IntegerField(
                label=lbl,
                required=False,
                help_text=p_help)

        elif p_type == 'double':
            new_field = forms.FloatField(
                label=lbl,
                required=False,
                help_text=p_help)

        elif p_type == 'string':
            new_field = forms.CharField(
                max_length=STRING_PARAM_MAX_LENGTH,
                strip=True,
                required=False,
                label=lbl,
                help_text=p_help)
        elif p_type == 'boolean':
            new_field = forms.BooleanField(
                required=False,
                label=lbl,
                help_text=p_help)
        else:  # p_type == 'datetime':
            new_field = forms.DateTimeField(
                required=False,
                label=lbl,
                widget=DateTimePickerInput(options=DATE_TIME_WIDGET_OPTIONS),
                help_text=p_help)

        return new_field 
Example #19
Source File: test_forms.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_to_python_no_trailing_commas(self):
        field = SimpleListField(forms.IntegerField())
        with pytest.raises(exceptions.ValidationError) as excinfo:
            field.clean("1,")
        assert excinfo.value.messages[0] == "No leading, trailing, or double commas." 
Example #20
Source File: test_forms.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_to_python_no_leading_commas(self):
        field = SimpleListField(forms.IntegerField())
        with pytest.raises(exceptions.ValidationError) as excinfo:
            field.clean(",1")
        assert excinfo.value.messages[0] == "No leading, trailing, or double commas." 
Example #21
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {'form_class': forms.IntegerField}
        defaults.update(kwargs)
        return super(IntegerField, self).formfield(**defaults) 
Example #22
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_prep_lookup(self, lookup_type, value):
        if ((lookup_type == 'gte' or lookup_type == 'lt')
                and isinstance(value, float)):
            value = math.ceil(value)
        return super(IntegerField, self).get_prep_lookup(lookup_type, value) 
Example #23
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_prep_value(self, value):
        value = super(IntegerField, self).get_prep_value(value)
        if value is None:
            return None
        return int(value) 
Example #24
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def validators(self):
        # These validators can't be added at field initialization time since
        # they're based on values retrieved from `connection`.
        range_validators = []
        internal_type = self.get_internal_type()
        min_value, max_value = connection.ops.integer_field_range(internal_type)
        if min_value is not None:
            range_validators.append(validators.MinValueValidator(min_value))
        if max_value is not None:
            range_validators.append(validators.MaxValueValidator(max_value))
        return super(IntegerField, self).validators + range_validators 
Example #25
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def _check_max_length_warning(self):
        if self.max_length is not None:
            return [
                checks.Warning(
                    "'max_length' is ignored when used with IntegerField",
                    hint="Remove 'max_length' from field",
                    obj=self,
                    id='fields.W122',
                )
            ]
        return [] 
Example #26
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def check(self, **kwargs):
        errors = super(IntegerField, self).check(**kwargs)
        errors.extend(self._check_max_length_warning())
        return errors 
Example #27
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {'form_class': forms.IntegerField}
        defaults.update(kwargs)
        return super(IntegerField, self).formfield(**defaults) 
Example #28
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get_internal_type(self):
        return "IntegerField" 
Example #29
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get_prep_lookup(self, lookup_type, value):
        if ((lookup_type == 'gte' or lookup_type == 'lt')
            and isinstance(value, float)):
            value = math.ceil(value)
        return super(IntegerField, self).get_prep_lookup(lookup_type, value) 
Example #30
Source File: test_fields_array.py    From richie with MIT License 5 votes vote down vote up
def test_fields_array_valid_int(self):
        """
        Happy path: the value is an array and all its items are valid as per the base_type
        """
        # Create an ArrayField instance with some params
        array_of_int = ArrayField(
            required=False, base_type=forms.IntegerField(min_value=1)
        )
        # The field is valid and returns cleaned data
        self.assertEqual(array_of_int.clean([1, 2, 3, 5, 7]), [1, 2, 3, 5, 7])