I need to display a foreignKey field as a selection field in Django template, which will show all the available records as a dropdown. On considering the case of querying to database every time on selecting the field, which is the best method to achieve above goal to make a selection field from ForeignKey field.
Asked
Active
Viewed 2,074 times
2 Answers
2
Use ModelChoiceField
https://docs.djangoproject.com/en/1.10/ref/forms/fields/#django.forms.ModelChoiceField
class MyForm(forms.ModelForm):
myfield = forms.ModelChoiceField(queryset=...)

Sardorbek Imomaliev
- 14,861
- 2
- 51
- 63
1
You should use first views to get that foreign key field and pass it over the context dict. to the template.
Inside Views.py
DEPENDENT_FILED = DB.OBJECT.ALL() // field which has all the drop-down values.
FR_FIELD = DB.OBJECT.GET(DB_OBJ_HAVING_FR) // selected drop-down from template
context['FR_FIELD'] = FR_FIELD
Inside example.html
{% if FR_FIELD %}
<select name="dropdown_field">
{%for fr_key in DEPENDENT_FILED %}
<option value="{{fr_key.field_name}}" {% if fr_key.field_name = FR_FIELD|add:0 %}selected{% endif %}>{{fr_key.option_name}}</option>
{% endfor %}
</select>

Viraj
- 228
- 5
- 14