1👍
✅
You can do this:
class StudentForm(forms.ModelForm)
student_percentile = forms.ModelChoiceField(queryset= Percentile.objects.all(), empty_label="--Select--")
class Meta:
model = Student
0👍
Assuming the list of percentile choices doesn’t change often, this blog post gives a good method for doing what you’re discussing.
http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/
It describes using a tuple of choices and feeding it to a CharField (or perhaps per Joseph Paetz’s comment above, you could use an IntegerField for more efficient sorting and aggregation, and so you’re not storing what’s really a numeric value as text).
With your case specifically, you could just add a ‘–Select–‘ option as the first option, perhaps with a value of ‘-1’ or something similar, so you can validate on that value when the form is submitted. If it’s -1, they didn’t pick anything.
PERCENTILE_CHOICES = (
(-1, '--Select--'),
(95, '95th Percentile'),
(80, '80th Percentile'),
...etc...
)
- [Answer]-How to query a tree structure in Django model
- [Answer]-Reuse custom form template in django
- [Answer]-Django attribute assignment, understanding the documentation
Source:stackexchange.com