Skip to content

Instantly share code, notes, and snippets.

@mnazim
Last active September 26, 2015 14:37
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mnazim/1112306 to your computer and use it in GitHub Desktop.
Make Django forms.ChoiceField accept choices from a very large data set(see: http://blog.ikraftsoft.com/post/1342312823/)
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)
from django import forms
class LazyChoiceField(forms.ChoiceField):
def __init__(self, *args, **kwargs):
super(LazyChoiceField, self).__init__(*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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment