表单中ModelChoiceField显示
我正在尝试创建一个简单的表单,用来连接两个模型(表格)。
这是我的模型声明:
model.py
class THost(models.Model):
name = models.CharField(max_length=45, blank=True)
Location = models.ForeignKey('TLocation', db_column='idLocation')
class TLocation(models.Model):
name = models.CharField(max_length=45, blank=True)
address = models.TextField(blank=True)
zipcode = models.CharField(max_length=45, blank=True)
city = models.CharField(max_length=45, blank=True)
country = models.CharField(max_length=45, blank=True)
这是我的 forms.py
class hostForm(forms.ModelForm):
Location = forms.ModelChoiceField(queryset=TLocation.objects.all())
class Meta:
model = THost
这是我的 views.py
form1 = hostForm()
if request.method == "POST":
form1 = hostForm(request.POST)
if form1.is_valid:
form1.save()
现在我遇到的问题是,在表单中有一个下拉列表,显示的内容是好几行“TLocation对象”。我不知道怎么才能简单地显示出 TLocation 的名字或城市。
谢谢你的帮助!
3 个回答
0
尝试自定义一个叫做 ModelChoiceField 的字段,并重写 label_from_instance 这个方法。这个方法会接收一个模型对象,然后应该返回一个合适的字符串来表示这个对象:
class MyModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return obj.name
class hostForm(forms.ModelForm):
Location = forms.MyModelChoiceField(queryset=TLocation.objects.all())
class Meta:
model = THost
1
谢谢你 @petkostas!我原本在找一些复杂的东西,但Python并不复杂 :)
这是我写的代码:
class TLocation(models.Model):
name = models.CharField(max_length=45, blank=True)
address = models.TextField(blank=True)
zipcode = models.CharField(max_length=45, blank=True)
city = models.CharField(max_length=45, blank=True)
country = models.CharField(max_length=45, blank=True)
def __unicode__(self):
return u'%s - %s' % (self.name, self.city)
结果是一个下拉列表,上面显示的是“名字 - 城市”
太棒了,谢谢你!
1
在你的 models.py 文件里:
在最上面:
from __future__ import unicode_literals
在你的模型类之前:
@python_2_unicode_compatible
class YourModel(models.Model):
还有在你的模型类里面:
def __str__(self):
"""
Return the representation field or fields.
"""
return '%s' % self.name