【问题标题】:Django one-to-many form issue with formDjango 一对多表单问题与表单
【发布时间】:2014-09-14 15:59:39
【问题描述】:

我创建了一个一对多的关系模型和一个表单。问题是当我加载表单时,它只列出了模型名称+“对象”而不列出字段中的实际数据。因此,如果我有一个包含 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

类 LocationForm(forms.ModelForm):

class Meta:
    model = Location

类 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>

【问题讨论】:

    标签: python django


    【解决方案1】:

    您需要在模型上声明__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
    

    确保你使用__str__ if you use python 3.x

    【讨论】:

      最近更新 更多