ModelForm:显示外键字段 [英] ModelForm: display foreign key field

查看:59
本文介绍了ModelForm:显示外键字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

models.py

models.py

class Manufacturers(models.Model):
    name = models.CharField(max_length=32)

class Cars(models.Model):
    producedby = models.ForeignKey(Manufacturers)

forms.py

class CreateCar(forms.ModelForm): 
    class Meta: 
        model = Cars

...在html页面上,"producedby"字段显示为"Manufacturer object"选项列表,这不是很有用,是否可以改为显示Manufacturer.name字段?我尝试了其他线程中建议的解决方案,但没有一个起作用.

... on the html page the "producedby" field appears like a list of "Manufacturer object" choices, which is not very useful, is it possible to display the Manufacturer.name field instead? I have tried solutions suggested in other threads but none of them worked.

非常感谢您的帮助

推荐答案

我通过重载__str__方法并按如下所示返回名称来修复它:

I fixed it by overloading the __str__ method and returning the name as follows:

class Manufacturers(models.Model):
    name = models.CharField(max_length=32)
    def __str__(self): return self.name

这篇关于ModelForm:显示外键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆