开发者

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' vali开发者_如何学运维dation rules of integer! field?

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


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)]


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.


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)])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜