Django Model Choice Field: Huge List of choices
Consider these 3 models:
# models.py
class City(models.Model):
name = models.CharField(max_length=50)
class Institute(models.Model):
name = models.CharField(max_length=100)
city = models.ForeignKey(City)
class Student(models.Model):
name = models.CharField(max_length=60)
roll = models.CharField(max_length=10)
institute = models.ForeignKey(Institute)
Now I am creating a model form to add/edit students but I provide the option to select city and institute to the user. So basically when a user selects city the corresponding institutes are displayed using JavaScript
# forms.py
class StudentForm(forms.ModelForm):
city = forms.ModelChoiceField(City)
institute = forms.ModelChoiceField(queryset=Institute.objects.all())
class Meta:
model开发者_如何学编程 = Student
But the number of institutes is over 3000. So what I want is to keep the choices as blank initially for institute field (coz they will be filled by the JavaScript once the user selects a City), but upon submitting the data, I get a "Select a valid choice" validation error. Any ideas how to tackle such problem?
Note: When I do NOT specify choices (for institute field) the web page size is 300KB and when I specify them the size of web page is 1.1MB
Apparently, I had to override the Choice widget and change its render method to display no options. Since choices argument is still provided, the validation error does not occur and I can freely use javascript to render institutes by the city selected.
I had the same issue, but overcomed it by setting widget.choices to []
class StudentForm(forms.ModelForm):
city = forms.ModelChoiceField(City)
institute = forms.ModelChoiceField(queryset=Institute.objects.all())
def __init__(self, *args, **kwargs):
super(StudentForm, self).__init__(*args, **kwargs)
self.fields['institute'].widget.choices = []
You should ensure that the Institute
values that get filled up in the select box should also have the primary key as the html id
attribute.
精彩评论