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

1👍

The easiest way to do it is to provide a string representation of your object, this would replace any where you access the class throughout your application

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)

From the 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.

👤Sayse

Leave a comment