I would like to display data from the table into Django Queryset Form with properly showing value and text of dropdown control.
Coding at Form:
self.fields['testing_field'].queryset = model_abc.objects.all().values_list('description', flat=True)
Result description is also value:
<select name="cars" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Result expection can set id as value with existing description:
<select name="cars" id="cars">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
How to set id as a value within the dropdown form of Django QuerySet ?
CodePudding user response:
You need to fetch both the description and the pk of the objects. that's easy enough:
possibles = model_abc.objects.all().values_list('pk', 'description')
You might convert this into a dynamic choices:
choices = ( (x['pk'], x['description']) for x in possibles )
or, you might iterate over possibles in your template
{% for option in possibles %}
<option value="{{option.pk}}">{{option.description}}</option>
{% endfor %}