[Fixed]-Django: Getting foreign key value to show in forms

1๐Ÿ‘

โœ…

If you want to change the display value for ModelChoiceField, you could easily define your own field and override label_from_instance method:

class CourseField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
         # return the field you want to display, which is Course
         return obj.Course

class EducationalRequirementForm(forms.ModelForm):
    Course = CourseField(queryset=Courses_list.objects.all())

Not related, but your are suffering from some poor coding styles. Models are python classes, so they should be like EducationalRequirement. Fields are python class attributes, they should be lower case with underscores like job_position. Check python PEP8 documentation for more code style information.

๐Ÿ‘คShang Wang

Leave a comment