In my Django project, I have a Students model with various fields. I created a ModelChoiceField form allowing users to select a record from the Students table via a dropdown.
forms.py:
class StudentChoiceField(forms.Form):
students = forms.ModelChoiceField(
queryset=Student.objects.values_list().order_by("last_name"),
empty_label="(select student)",
widget=forms.Select(attrs={"onChange":'refresh()'})
)
def __init__(self, *args, **kwargs):
super(StudentChoiceField, self).__init__(*args, **kwargs)
self.fields['students'].queryset = Student.objects.all().order_by("last_name")
self.fields['students'].label_from_instance = lambda obj: "%s %s" % (obj.last_name, obj.first_name)
To display just two selected model fields in the dropdown, I customized the label_from_instance method even though there are 11 total model fields.
Upon selecting a student, I aim to update textfields on the page with the rest of the model's fields. I've implemented a Javascript function called refresh(), triggered by onChange event of the StudentChoiceField form.
index.html (all_students_choice references the StudentChoiceField form):
{% extends "base.html" %}
{% block content %}
<body>
<script>
function refresh(){
var id = document.getElementById("id_students").value;
console.log(id);
}
</script>
<div class="container">
<form method=POST action="">
{% csrf_token %}
{{ all_students_choice }}
</form>
</div>
</body>
{% endblock %}
After testing in the browser console and verifying that the function properly retrieves the value of the ModelChoiceField form upon selection, I now seek advice on how to populate additional textfields on the page with the remaining Student model fields (excluding first and last name). Should these be passed as parameters to the Javascript function, or is there a better approach?