开发者

ModelForm django select html problem

I'm facing a little problem with my modelForm , it works but if i try to use a custom html i get a error when i try to iterate over form.bairro.

My Model:

    class Bairro(models.Model):
       bairro = models.CharField(max_length=50)

       def __unicode__(self):
         return self.bairro
       class Meta:
         db_table = 'bairro'

    class Cliente(models.Model):
     nome = models.CharField(max_length=80)
     bairro = models.ForeignKey(Bairro ,  on_delete=models.PROTECT)
     endereco = models.CharField(max_length=100)
     telefone = models.CharField(max_length=8,null=True)

     def __unicode__(self):
         return self.nome

     class Meta:
       ordering = ['nome']
       db_table = 'cliente'

My form :

    from cliente.models import Cliente,Bairro
    from django.forms import ModelForm

    class ClienteForm(ModelForm):
     class Meta:
        model = Cliente

my html :

         <select name="bairro" id="id_bairro">
                {% for b in      form.bairro%}                  
                <option value="{{b.id}}">{{b.bairro}}</option>
                {% endfor%}
            </select>

what am i missing ? i dont want to use form.as_p() or form.开发者_C百科as_table() , i want to write my own html .....already use custom html with normal forms and it works perfectly.


http://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField.queryset

Use the field's queryset attribute.

{% for b in form.bairro.field.queryset %}
     <option value="{{b.id}}">{{b.bairro}}</option>
{% endfor%}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜