窗体模型选项字段显示

2024-09-26 22:07:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图建立一个简单的表单链接到两个模型表。 以下是我的模型声明:

在模型.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)

我的表单.py在

^{pr2}$

我的视图.py在

   form1 = hostForm()
   if request.method == "POST":
      form1 = hostForm(request.POST)
      if form1.is_valid:
        form1.save()

问题是,在表单中,我现在有一个下拉列表,显示了几个带有“TLocation object”的对齐方式。 我不知道如何简单地显示位置名称或城市

谢谢你的帮助!在


Tags: namepy模型true表单modelmodelslength
3条回答

尝试自定义ModelChoiceField并重写来自_实例的label_。此方法将接收模型对象,并应返回适合表示该对象的字符串:

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

谢谢@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)

结果是一个带有“name-city”的下拉列表

太棒了谢谢

在你的模型.py公司名称:

在顶部:

from __future__ import unicode_literals

在模型课之前:

^{pr2}$

在你的模型课里:

def __str__(self):
    """
    Return the representation field or fields.
    """
    return '%s' % self.name

相关问题 更多 >

    热门问题