2011-02-16 2 views
0

J'ai un nombre entier de champs, mais leur widget par défaut est TextInput. Je veux utiliser le widget Select, mais je dois fournir explicitement des valeurs possibles.Champ personnalisé ou widget Django?

Est-il possible qu'ils soient générés automatiquement à partir des règles de validation 'initial', 'min_value' and 'max_value' du champ integer!? Dois-je créer mon propre champ, widget, ou les deux? Et comment?

Répondre

2

Vous pouvez simplement le faire sous la forme __init__ méthode.

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

Etes-vous sûr my_int.choices = ... est bon endroit pour définir des valeurs, parce que pour moi ce n » ai pas t travail. Je n'arrive seulement à le faire en utilisant widget = forms.Select (choix = ...) –

1

Voilà comment je fais en général des choix spéciaux:

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

Plutôt que introspectant le champ modèle que je viens de mettre valeurs min et max dans une variable au sommet pour la simplicité.

Au lieu d'utiliser un IntegerField, j'utilise un champ ChoiceField. Consultez le ChoiceField documentation pour plus de détails. Ils ne sont pas difficiles à utiliser.

1

Vous pouvez définir le champ sur la méthode init de la forme, comme ceci:

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