amit_183
amit_183

Reputation: 981

getting tables values in dropdown list in django forms

I want to get the values of database in the forms field: here is the code:

Models.py

class GatewayDetails(models.Model):
    gateway_id = models.IntegerField(primary_key=True)
    gateway_name = models.CharField(max_length=256L)
    class Meta:
        db_table = 'gateway_details'

class GatewayProtocolMapping(models.Model):
    gateway = models.ForeignKey(GatewayDetails)
    protocol = models.ForeignKey('ProtocolType')
    class Meta:
        db_table = 'gateway_protocol_mapping'

Views.py

  if request.method=="POST":
        add_gateway_details_form=Add_Gateway_Details(request.POST)
        if add_gateway_form.is_valid():
            success=True

        gateway_name=add_gateway_form.cleaned_data['gateway_name']

        else:
            add_gateway_details_form=Add_Gateway_Details()
else:
    add_gateway_details_form=Add_Gateway_Details()

          ctx={'add_gateway_protocol_form':add_gateway_protocol_form,'add_gateway_details_form':add_gateway_details_form,}

forms.py

   class Add_Gateway_Details(forms.ModelForm):
    class Meta:
    model=GatewayDetails
    exclude=('gateway_id',)
   class Add_Gateway_Protocol(forms.ModelForm):
    class Meta:
    model=GatewayProtocolMapping
    exclude=('gateway',)

template.html:

  <form action="." method="POST">
            <table>
                <hr>
                <tr>
                    <th class="label label-info">Gateway Name</th>
                    <td>{{ add_gateway_details_form.gateway_name }}</td>
                </tr>
                <tr>
                    <th class="label label-info">Gateway Protocol</th>
                    <td>{{ add_gateway_protocol_form.protocol }}</td>
                </tr>

            <input type="submit" value="send">
        </form>

Gateway protocol field is displayed as dropdownlist...but the values in the dropdownlist is the Object of ProtocolType but i want the values from the tables and not the object...

Upvotes: 0

Views: 1744

Answers (1)

Rohan
Rohan

Reputation: 53366

In your ProtocolType model add __unicode__() method to return appropriate string for the protocol. That string will be displayed in the dropdown field.

Example

class ProtocolType(models.Model):
   #your fields
   def __unicode__(self):
        return self.name # if you have char name field in protocol, otherwise use appropriate field(s) to construct the string.

Upvotes: 1

Related Questions