Django 表单字段显示名称
Django form field display name
我正在尝试在模型的基础上制作表格。问题是,当我通过 django shell
创建 category
时,让我们说 "Wedding" 类别,具有 id=1
和 name = "weddings"
,当我在下拉列表中显示它时(在html 形式)它显示为 Categories object (1)
我希望它按名称显示,即 weddings
.
与 documentation 一样,我知道我可以在 Meta
形式 class 中附加 labels
,但我不完全理解如何动态显示所有类别名称而不是类别对象 1,2,3,4。
Models.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)
Forms.py
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = ['category','person','owner']
所以渲染表单时的实际结果是:
Category:(dropdown) - Categories object (1)
想要的结果:
Category:(dropdown) - weddings
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
只需将这个小魔法函数添加到您的模型中即可 类。
我正在尝试在模型的基础上制作表格。问题是,当我通过 django shell
创建 category
时,让我们说 "Wedding" 类别,具有 id=1
和 name = "weddings"
,当我在下拉列表中显示它时(在html 形式)它显示为 Categories object (1)
我希望它按名称显示,即 weddings
.
与 documentation 一样,我知道我可以在 Meta
形式 class 中附加 labels
,但我不完全理解如何动态显示所有类别名称而不是类别对象 1,2,3,4。
Models.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)
Forms.py
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = ['category','person','owner']
所以渲染表单时的实际结果是:
Category:(dropdown) - Categories object (1)
想要的结果:
Category:(dropdown) - weddings
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
只需将这个小魔法函数添加到您的模型中即可 类。