Python django.forms.IntegerField() Examples

The following are 30 code examples for showing how to use django.forms.IntegerField(). 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: django-seo   Author: whyflyru   File: admin.py    License: 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 2
Project: starthinker   Author: google   File: forms_json.py    License: 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 3
Project: pycon   Author: pythonitalia   File: test_mutations.py    License: 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 4
Project: pycon   Author: pythonitalia   File: test_mutations.py    License: 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 5
Project: pycon   Author: pythonitalia   File: test_mutations.py    License: 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 6
Project: python   Author: Yeah-Kun   File: __init__.py    License: 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 7
Project: registrasion   Author: chrisjrn   File: forms.py    License: 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 8
Project: registrasion   Author: chrisjrn   File: forms.py    License: Apache License 2.0 6 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 9
Project: registrasion   Author: chrisjrn   File: forms.py    License: Apache License 2.0 6 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 10
Project: python2017   Author: bpgc-cte   File: __init__.py    License: 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
Project: helfertool   Author: helfertool   File: set.py    License: 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 12
Project: donation-tracker   Author: GamesDoneQuick   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, prizes, *args, **kwargs):
        super(DrawPrizeWinnersForm, self).__init__(*args, **kwargs)
        self.choices = []
        for prize in prizes:
            self.choices.append(
                (
                    prize.id,
                    mark_safe(
                        format_html(
                            '<a href="{0}">{1}</a>', viewutil.admin_url(prize), prize
                        )
                    ),
                )
            )
        self.fields['prizes'] = forms.TypedMultipleChoiceField(
            choices=self.choices,
            initial=[prize.id for prize in prizes],
            coerce=lambda x: int(x),
            label='Prizes',
            empty_value='',
            widget=forms.widgets.CheckboxSelectMultiple,
        )
        self.fields['seed'] = forms.IntegerField(
            required=False,
            label='Random Seed',
            help_text="Completely optional, if you don't know what this is, don't worry about it",
        ) 
Example 13
Project: donation-tracker   Author: GamesDoneQuick   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(PrizeAcceptanceForm, self).__init__(*args, **kwargs)
        self.accepted = None

        if 'data' in kwargs and kwargs['data'] is not None:
            if 'accept' in kwargs['data']:
                self.accepted = True
            elif 'deny' in kwargs['data']:
                self.accepted = False

        self.fields['count'] = forms.ChoiceField(
            initial=self.instance.pendingcount,
            choices=list([(x, x) for x in range(1, self.instance.pendingcount + 1)]),
            label='Count',
            help_text='You were selected to win more than one copy of this prize, please select how many you would like to take, or press Deny All if you do not want any of them.',
        )
        if self.instance.pendingcount == 1:
            self.fields['count'].widget = forms.HiddenInput()
        self.fields['total'] = forms.IntegerField(
            initial=self.instance.pendingcount,
            validators=[positive],
            widget=forms.HiddenInput(),
        )
        self.fields['comments'] = forms.CharField(
            max_length=512,
            label='Notes',
            required=False,
            help_text='Please put any additional notes here (such as if you have the option of customizing your prize before it is shipped, or additional delivery information).',
            widget=forms.Textarea(attrs=dict(cols=40, rows=2)),
        ) 
Example 14
Project: coursys   Author: sfu-fas   File: text.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_entry_field(self, questionanswer=None, student=None):
        resp_type = self.question.config.get('resp_type', 'float')
        if questionanswer:
            initial = questionanswer.answer.get('data', '')
        else:
            initial = None

        if resp_type == 'int':
            field = forms.IntegerField(required=False, initial=initial)
        else:
            field = forms.FloatField(required=False, initial=initial)

        field.widget.attrs.update({'class': 'numeric-answer'})
        return field 
Example 15
Project: heltour   Author: cyanfish   File: forms.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        reg = kwargs.pop('registration')
        super(ApproveRegistrationForm, self).__init__(*args, **kwargs)

        workflow = ApproveRegistrationWorkflow(reg)

        self.fields['send_confirm_email'].initial = workflow.default_send_confirm_email
        self.fields['invite_to_slack'].initial = workflow.default_invite_to_slack

        section_list = reg.season.section_list()
        if len(section_list) > 1:
            section_options = [(season.id, season.section.name) for season in section_list]
            self.fields['section'] = forms.ChoiceField(choices=section_options,
                                                       initial=workflow.default_section.id)

        if workflow.is_late:
            self.fields['retroactive_byes'] = forms.IntegerField(initial=workflow.default_byes)
            self.fields['late_join_points'] = forms.FloatField(initial=workflow.default_ljp) 
Example 16
Project: heltour   Author: cyanfish   File: forms.py    License: MIT License 5 votes vote down vote up
def __init__(self, is_team_league, round_to_close, round_to_open, season_to_close, *args,
                 **kwargs):
        super(RoundTransitionForm, self).__init__(*args, **kwargs)

        if round_to_close is not None:
            self.fields['complete_round'] = forms.BooleanField(initial=True,
                                                               required=False,
                                                               label='Set round %d as completed' % round_to_close.number)
            self.fields['round_to_close'] = forms.IntegerField(initial=round_to_close.number,
                                                               widget=forms.HiddenInput)

        if season_to_close is not None:
            self.fields['complete_season'] = forms.BooleanField(initial=True,
                                                                required=False,
                                                                label='Set %s as completed' % season_to_close.name)

        if round_to_open is not None:
            if is_team_league:
                self.fields['update_board_order'] = forms.BooleanField(initial=True,
                                                                       required=False,
                                                                       label='Update board order')
            self.fields['generate_pairings'] = forms.BooleanField(initial=True,
                                                                  required=False,
                                                                  label='Generate pairings for round %d' % round_to_open.number)
            self.fields['round_to_open'] = forms.IntegerField(initial=round_to_open.number,
                                                              widget=forms.HiddenInput) 
Example 17
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.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 18
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.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 19
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.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 20
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.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 21
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: 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 22
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: 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 23
Project: anytask   Author: znick   File: forms.py    License: MIT License 5 votes vote down vote up
def default_teacher_forms_factory(course, group, teacher=None, post_data=None):
    teacher_id = 0
    if teacher:
        teacher_id = teacher.id

    class DefaultTeacherForm(forms.Form):
        course_id = forms.IntegerField(initial=course.id, widget=forms.HiddenInput)
        groups_id = forms.IntegerField(initial=group.id, widget=forms.HiddenInput)
        teacher = forms.ChoiceField(initial=teacher_id, choices=get_teacher_choises(course), label="")

    return DefaultTeacherForm() 
Example 24
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 5 votes vote down vote up
def rel_db_type(self, connection):
        return IntegerField().db_type(connection=connection) 
Example 25
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 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
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_internal_type(self):
        return "IntegerField" 
Example 27
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {'form_class': forms.IntegerField}
        defaults.update(kwargs)
        return super().formfield(**defaults) 
Example 28
Project: bioforum   Author: reBiocoder   File: __init__.py    License: 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 29
Project: django-twitter-stream   Author: michaelbrooks   File: fields.py    License: MIT License 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {'min_value': 0,
                    'max_value': PositiveBigAutoField.MAX_BIGINT * 2 - 1,
                    'form_class': forms.IntegerField }
        defaults.update(kwargs)
        return super(PositiveBigAutoField, self).formfield(**defaults) 
Example 30
Project: django-twitter-stream   Author: michaelbrooks   File: fields.py    License: MIT License 5 votes vote down vote up
def db_type(self, connection):
        # The database column type of a ForeignKey is the column type
        # of the field to which it points. An exception is if the ForeignKey
        # points to an AutoField/PositiveIntegerField/PositiveSmallIntegerField,
        # in which case the column type is simply that of an IntegerField.
        # If the database needs similar types for key fields however, the only
        # thing we can do is making AutoField an IntegerField.
        rel_field = self.related_field
        if isinstance(rel_field, PositiveBigAutoField):
            return PositiveBigIntegerField().db_type(connection=connection)
        return rel_field.db_type(connection=connection)