public
Created — forked from mnazim/forms.py

Make Django forms.ChoiceField accept choices from a very large data set(see: http://blog.ikraftsoft.com/post/1342312823/)

  • Download Gist
forms.py
Python
1 2 3 4 5 6 7 8 9 10
from django import forms
list_of_choices = (
(1, 'Choice 1'),
(2, 'Choice 2'),
(3, 'Choice 3'),
# ...
(n, 'Choice n'),
)
class MyForm(forms.Form):
my_choice_field = forms.ChoiceField(choices=list_of_choices)
forms_updated.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
from django import forms
 
class LazyChoiceField(forms.ChoiceField):
def __init__(self, choices=(), required=True, widget=None, label=None,
initial=None, help_text=None, *args, **kwargs):
super(LazyChoiceField, self).__init__(required=required, widget=widget,
label=label, initial=initial,
help_text=help_text, *args, **kwargs)
 
def valid_value(self, value):
# your custom validation code for "value" argument goes here
# return True if value is valid else return False
 
list_of_choices = (
(1, 'Choice 1'),
(2, 'Choice 2'),
(3, 'Choice 3'),
# ...
(n, 'Choice n'),
)
 
class MyForm(forms.Form):
my_choice_field = LazyChoiceField(choices=list_of_choices)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.