Reputation: 19
I'm new with Python and Django. I'd like to use combo box with ModelChoiceField like below.
school = forms.ModelChoiceField(queryset=School.objects.all())
The school object have a 'id', 'Name', 'Domain' fields but when I render the form in the html it show like below.
<label for="id_school">School:</label>
<select id="id_school" name="school">
<option value="" selected="selected">---------</option>
<option value="3">School object</option>
</select>
I'd like to make the text from 'Name' field and make the first row to be selected. Also it would be great if you have any reference site some one like me!
Thanks!
Upvotes: 0
Views: 7075
Reputation: 912
If you want to have the first object selected by default then you should so something like that in your form model:
school = forms.ModelChoiceField(queryset=School.objects.all(), initial=0)
If you want to set the initial value from an instance of your model you can check accepted answer here SO accepted answer
Upvotes: 3
Reputation: 25539
It shows School object
because that's how the School
objects are rendered. If you don't specify anything in School
model then that's how django would render objects.
What you need to do is to define __str__
method for School
model. The __str__()
method is defined as:
The
__str__()
method is called whenever you callstr()
on an object. Django usesstr(obj)
in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object. Thus, you should always return a nice, human-readable representation of the model from the__str__()
method.
class School(models.Model):
def __str__(self)
return self.name
Django doc about __str__
.
Upvotes: 5