Django - select options

0

I'm trying to put the names of the coordinators in the options of a select looking for the database, I've already researched and it seems that there is another way to use the select in django, but it was not very clear, so I'm posting here my code to see if someone can clear up my doubts.

This is the part of views:

contexto ={
    'coordenadores': Coordenador.objects.all()
}
...
return render(request, 'formDisciplina.html', contexto)

Here is the template below:

<p><label name='idcoordenador'>Coordenador: </label>
    <select name='idcoordenador'>
        <option>-----Selecione-----</option>
        {% for a in coordenadores %}
            <option values= {{ a.id }}> {{ a.name }} </option>
        {% endfor %}

    </select>
</p>
    
asked by anonymous 08.05.2018 / 00:45

1 answer

0
#arquivo forms.py
from django import forms

class MeuForm(forms.Form):
    #no choices eu fiz um list comprehension que apenas gera um list [a,b,c...z] que vai ser renderizado no select
    coordenadores = forms.ChoiceField(choices=[('0', '--Selecione--')]+    [(coordenador.id, coordenador.name) for coordenador in Coordenador.objects.all()])

In your view, you create an instance of form and switch to the template formDisciplina.html

#views.py
from forms import MeuForm
from models import Coordenador
contexto ={
'meu_form': MeuForm()
}
...
return render(request, 'formDisciplina.html', contexto)

In the template just call my_form

<form action="/minha_acao/" method="post">
    {% csrf_token %}
    {{ meu_form }}
    <input type="submit" value="Submit" />
</form>
    
08.05.2018 / 18:40