How can I set form multiple choice options with values from a database?

Is that the complete form shown in the snippet at the top, or is there more to the form than that.

Also, have you verified that in your test case, currentteacher contains an iterable for any given request? (In other words, have you verified that your query works for the information available at the point where the query is running?)

This query can result in an empty result set if either the current user isn’t a teacher or has a blank username.

Since there’s only one Teacher for any given username, I would suggest that you change the filter to a get to retrieve the specific Teacher object, access the teacher_id field directly, pass it to the form, and change your filter in the Class query to an exact match.

Also note that since there’s a foreign key relationship between Teacher and Class, you don’t need to write an explicit query to retrieve those related objects.

Given an instance of Teacher named teacher, then teacher.class_set.all() is the set of all classes related to teacher. You can iterate over that set directly.

2 Likes