不显示 Django ModelForm 外键值

Django ModelForm foreign key values are not displayed

我是 Django 的新手,我正在尝试使用模型表单创建表单。该表单有一个外键值(connection_type 下面的 forms.py)并且它没有显示它所引用的值。

对于下图,列,

连接名称:已显示

连接类型:文本框未出现

端点:显示

Image from the browser

forms.py

class ConnectionForm(forms.ModelForm):

connection_type = forms.ModelChoiceField(queryset=ConnectionTypes.objects.all(), to_field_name='connection_type_id')

class Meta:
    model = ConnectionDetails
    exclude = ['connection_id','last_update_date']

Models.py

class ConnectionDetails(models.Model):
      connection_id = models.IntegerField(primary_key=True,default=re_sequence('connection_seq'))
      connection_name = models.CharField(max_length=200)
      connection_type = models.IntegerField() 
      endpoint = models.CharField(max_length=100)
      port = models.IntegerField()
      login_id = models.CharField(max_length=100)
      login_password = fields.CharPGPPublicKeyField(max_length=100)
      connection_string_1 = fields.CharPGPPublicKeyField(max_length=100)
      connection_string_2 = fields.CharPGPPublicKeyField(max_length=100)
      connection_string_3 = fields.CharPGPPublicKeyField(max_length=100)
      aws_region = models.CharField(max_length=20)
      owner_id = models.IntegerField()
      last_update_date = models.DateTimeField(default=dbcurr_ts)
      working_schema = models.CharField(max_length=100)
      service = models.CharField(max_length=100)

      def generate_enc(mystrenc):
          return 'pass'

      class Meta:
            managed = False
            db_table = 'connection_details'
            verbose_name = 'connection_details'
            verbose_name_plural = 'connection_details'

class ConnectionTypes(models.Model):
      connection_type_id = models.IntegerField(primary_key=True,default=re_sequence('connection_type_seq'))
      connection_type_name = models.CharField(max_length=100)
      connection_type_desc = models.CharField(max_length=300)
      connection_type_category = models.CharField(max_length=100)
      last_update_date = models.DateTimeField(default=dbcurr_ts)
      class Meta: 
            managed = False
            db_table ='connection_types'
            verbose_name = 'connection_types'
            verbose_name_plural = 'connection_types'

你能告诉我我犯了什么错误吗?

一个问题是 connecton_types 的模型字段采用 IntegerField。然而,您在表单中为它提供了一个 ModelChoiceField。我认为如果您将 connection_type 设置为 models.ForeignKey(ConnectionType, on_delete=models.CASCADE) 或 models.py 中的类似内容,它应该会更好用。这样 ConnectionType 直接链接到您拥有的任何 ConnectionDetails。