Django ModelForm foreign key values are not displayed

Am new to Django, and I am trying to create a form using model form. The form has a foreign key value (connection_type below in forms.py) and it's not displaying the values it is referring to.

For the image below, the columns,

Connection name: displayed

Connection type: text box has not appeared

Endpoint: displayed

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'

Can you please let me know what is mistake am making?

Upvotes: 0

Views: 594

Answers (1)

dbo123
dbo123

Reputation: 113

One issue is that the model field for connecton_types takes an IntegerField. Yet, you are giving it a ModelChoiceField in the form. I think if you set connection_type as models.ForeignKey(ConnectionType, on_delete=models.CASCADE) or something similar in your models.py, it should work better. This way the ConnectionType is directly linked to whatever ConnectionDetails you have.

Upvotes: 1

Related Questions