Dev
Dev

Reputation: 70

Using Foreign Key on Django model to populate select input

im having problems finding out on the documentation how to solve my problem so im posting here: I have 3 Models one for a class room with its attributes, one for students and the last one a relation of the room and the student. So on the template i want it to show a select button with a option value being the student id and the label being the student name

on my models.py i have this:

student_id = models.ForeignKey('Student', verbose_name=u"Student")

on my template.html i just call the field:

  {{ field }}

and the result that i get is:

<select name='student_id'>
  <option value='1'>Student object</option>
</select>

is there a way that i can preset the value and label like its done using choices for static data? to something like this:

STUDENT_CHOICES =(
    (model.student.id , model.student.name),
)
student_id = models.ForeignKey('Student', verbose_name=u"Student",, choices=STUDENT_CHOICES)

let me know if im not clear enough on the question since im fairly new to python and django

Upvotes: 0

Views: 1898

Answers (1)

Dev
Dev

Reputation: 70

Turned out all i had to do was to set the default value to be returned by adding a unicode function to each model:

def __unicode__(self):
    return self.student_name

And the full model code below:

Class StudentRoom(models.Model):
    student_id  = models.ForeignKey('Student')
    room_id  = models.ForeignKey('Room')

Class Student(models.Model):
    student_name = models.CharField(max_length=100)
    student_email = models.CharField(max_length=100)

  def __unicode__(self):
    return self.student_name

Class Room(models.Model):
    room_name = models.CharField(max_length=100)
    room_faction = models.CharField(max_length=100)

  def __unicode__(self):
    return self.room_name

Upvotes: 1

Related Questions