Django表单字段显示名称

时间:2018-05-15 10:56:18

标签: django forms models

我试图在模型的基础上制作表格。麻烦的是,当我通过category创建django shell时,请说" Wedding"类别,id=1name = "weddings",当我在下拉列表中显示(以html格式)时,它显示为Categories object (1),我希望它显示为名称,即{ {1}}。

documentation中一样,我知道我可以在weddings表单类中附加labels,但我不完全理解如何动态显示所有类别名称而不是类别对象1,2,3,4。

  

Models.py

Meta
  

Forms.py

class categories(model.Model):
    id = models.AutoField(primary_key =True)
    name = models.Charfield(max_length = 50)

class Event(models.Model):
    id = models.AutoField(primary_key =True)
    category = models.ForeignKey(Categories,on_delete=models.SET_NULL,null = True)
    owner = models.Charfield(max_length = 50)

因此渲染表单时的实际结果是:

class EventForm(forms.ModelForm):
class Meta:
    model = Event
    fields = ['category','person','owner']

期望的结果:

Category:(dropdown) - Categories object (1)

1 个答案:

答案 0 :(得分:0)

class categories(model.Model):
    id = models.AutoField(primary_key =True)
    name = models.Charfield(max_length = 50)

    def __str__(self):
        return self.name

class Event(models.Model):
    id = models.AutoField(primary_key =True)
    category = models.ForeignKey(Categories,on_delete=models.SET_NULL,null = True)
    owner = models.Charfield(max_length = 50)


    def __str__(self):
        return self.owner

只需将这些小魔术函数添加到模型类中即可。