使用通过外键链接的 table 中的数据预填充表单字段

Pre-populate form field with data from table linked via foreign key

可能是一个非常新手的 Django 问题,但这里是。在我的 Django 项目中,我的模型中有这个

#models.py
class Classes(models.Model):
        classcode = models.CharField(max_length=15)
        classname = models.TextField()
        students = models.ManyToManyField(User)

class Test(models.Model):
        classes = models.ForeignKey(Classes, on_delete=models.CASCADE)
        name = models.TextField(max_length=100)
        points = models.ManyToManyField(User, default=0)

我还有一个测试表格,它是:

#forms.py
class TestForm(forms.ModelForm):
    class Meta:
        model = Test
        fields = ('classes', 'name')

当我进入实际表格时,TestForm 中 'classes' 的下拉菜单仅显示 'Classes object' 我在数据库中的 'Classes' 数量.我想更改它,以便表格列出 类 的名称,这些名称存储在 'Classes' 模型中作为 'classname'

谁能给我指出正确的方向?

最简单的方法是提供对象的字符串表示,这将替换您在整个应用程序中访问 class 的任何地方

class Classes(models.Model):
    classcode = models.CharField(max_length=15)
    classname = models.TextField()
    students = models.ManyToManyField(User)

    def __str__(self):
        return "{0}: {1}".format(self.classcode, self.classname)

来自docs

The __str__ (__unicode__ on Python 2) method of the model will be called to generate string representations of the objects for use in the field’s choices; to provide customized representations, subclass ModelChoiceField and override label_from_instance.