我创建了一对多关系模型和表单。问题是,当我加载表单时,它只列出模型名称+' object'不列出字段中的实际数据。所以如果我有一个包含10个位置的Locations类。在个人表单中,我会得到一个带有“位置对象”的下拉框。里面没有地点列表。
models.py
class Location(models.Model):
location_name = models.CharField()
ect
class Person(models.Model):
location = models.ForeignKey(Location)
name = models.CharField()
form.py
class LocationForm(forms.ModelForm):
class Meta:
model = Location
class PersonForm(forms.ModelForm):
class Meta:
model = Person
html的
<form action="/persons/get/person/create/" method="post" role="form">{% csrf_token %}
{{form.as_p}}
<input type="submit" name="submit" value="Create person">
</form>
答案 0 :(得分:3)
您需要在模型上声明__unicode__
method。
class Location(models.Model):
location_name = models.CharField()
def __unicode__(self): #or __str__ for python 3.x
return u'%s' % self.location_name #Or whatever field
class Person(models.Model):
location = models.ForeignKey(Location)
name = models.CharField()
def __unicode__(self): #or __str__ for python 3.x
return u'%s' % self.name #or whatever field