Django - select options

Asked

Viewed 2,510 times

2

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

This is the view part:

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

Here below is the template:

<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>
  • Look at this other question, I believe it satisfies your.

  • I already searched but it was not very clear, I create the class in the same views ? And in the options I can insert the data of a comic with a for ?

  • The way you did it’s okay too. The way Isael pointed out is by using Django Forms that takes care of rendering the form elements for you but this takes a little time to understand how Forms work.

2 answers

4

#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 a form instance and move to the formDiscipline.html template

#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 meu_form

<form action="/minha_acao/" method="post">
    {% csrf_token %}
    {{ meu_form }}
    <input type="submit" value="Submit" />
</form>
  • got it, creates in views a class inheriting Forms. Form and then I use the Choicefield method.. now it’s much clearer thank you very much

  • good, it worked for me. Now I need to learn how to put other things in the form. For example: placeholder.

2

It’s been a long time. But it’s a simpler way to go

View:

task = Task.objects.all()

    data = {
        'task': task
    }
    return render(request, 'index.html', data)

Html:

<select class="form-control form-control-sm">
    <option>Selecione</option>
    {% if task %}
        {% for item in task %}
            <option>{{ item.TaskName }}</option>
        {% endfor %}
     {% else %}
     {% endif %}
 </select>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.