在django表单的下拉列表中获取表值

时间:2013-11-28 04:52:31

标签: python django

我想在表单字段中获取数据库的值:  这是代码:

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>

网关协议字段显示为下拉列表...但是下拉列表中的值是ProtocolType的对象,但我想要表中的值而不是对象......

1 个答案:

答案 0 :(得分:1)

ProtocolType模型中添加__unicode__()方法以返回协议的相应字符串。该字符串将显示在下拉字段中。

实施例

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.