Julian Popov
Julian Popov

Reputation: 17471

Django custom field or widget?

I have an integer fields, but their default widget is TextInput. I want to use Select widget, but I have to explicitly provide possible values.

Is it possible they to be automatically generated from 'initial', 'min_value' and 'max_value' validation rules of integer! field?

Do I have to make my own field, widget, or both? And how?

Upvotes: 0

Views: 939

Answers (3)

gladysbixly
gladysbixly

Reputation: 2659

You can define the field on the form's init method, like so:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    initial = 40
    min_value = 10
    max_value = 100

    self.fields['the_field'] = forms.ChoiceField(choices=range(min_value, max_value + 1), initial=initial, validators=[MinValueValidator(min_value), MaxValueValidator(max_value)])

Upvotes: 1

Kekoa
Kekoa

Reputation: 28250

This is how I generally do special choices:

def MyForm(forms.Form):
   INTEGER_CHOICES = [(i, i) for i in range(MIN_VALUE, MAX_VALUE)]
   my_integer = forms.ChoiceField(choices=INTEGER_CHOICES)

Rather than introspecting the model field I just put min and max values in a variable at the top for simplicity.

Instead of using an IntegerField, I use a ChoiceField. Check out the ChoiceField documentation for details. They are not difficult to use.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599956

You could just do it in the form __init__ method.

def MyForm(forms.Form):
   my_integer = forms.IntegerField(min_value=0, max_value=10, widget=forms.Select)

   def __init__(self, *args, **kwargs):
       super(MyForm, self).__init__(*args, **kwargs)
       my_int = self.fields['my_integer']
       my_int.choices = [(i, i) for i in range(my_int.min_value, my_int.max_value)]

Upvotes: 2

Related Questions