Selectively filling an HTML select from a parameter

Asked

Viewed 38 times

0

I have a Django view that queries the database and returns the result to a "query courses.html" file where a select is populated.

view py.

def consulta_cursos(request):
        if campus_id == '605':
            with connection.cursor() as cursor:
                cursor.execute("SELECT id_curso, campus, nome FROM curso WHERE campus_id = 605")
                rows = namedtuplefetchall(cursor);
                context = {'cursos': rows}
            return render(request, 'sistema/consulta_cursos.html', context)
        else:
            with connection.cursor() as cursor:
                cursor.execute("SELECT id_curso, nome FROM curso WHERE campus_id = %s", [campus_id])
                rows = namedtuplefetchall(cursor);
                context = {'cursos': rows}
            return render(request, 'sistema/consulta_cursos.html', context)

query.html.

{% for curso in cursos %}
    <option value="{{ curso.id_curso }}">{{ curso.campus }} - {{ curso.nome }}</option>
{% endfor %}

However, in the html file I need the select options to be different according to the value of the campus_id. Thus:

se campus_id == '605' 
  options deve ser: '<option value="{{ curso.id_curso }}">{{ curso.campus }} - {{ curso.nome }}</option>'
senão
  options deve ser: '<option value="{{ curso.id_curso }}">{{ curso.nome }}</option>'

But I don’t know how to do it inside {% for curso in cursos %} .... {% endfor %}

I’m starting out and this is my first project, so thank you for your help.

1 answer

1


You can add in the campus table a column with the boolean value that would indicate how it will be shown. Ex: You create a bool column that has the name displa_campus (or something like that) and in the template you send .

{% for curso in cursos %}
    {% if mostrar_campus %}
       <option value="{{ curso.id_curso }}">{{ curso.campus }} - {{ curso.nome}}</option>
    {% else %}
       <option value="{{ curso.id_curso }}">{{ curso.nome }}</option>
    {% endif %}
{% endfor %}

Of course, you need to call campus show on select.

  • Hi Yuri, thanks for the answer, but unfortunately I can not change the table structure in the bank, this is not an option. Now, your suggestion might help me if somehow I can test the campus_id where you test mostrar_campus. I can access the value of campus_id in the archive consulta_campus.html through sessionStorage.getItem("campus_id"). Have some way to use this within the IF that tests which option will be used?

  • After some attempts I managed to solve the problem using Yuri’s tip and making a simple modification in the view at: context = {'cursos': rows, "mostrar_campus": "True"}. I added the parameter that I will test and I can access it in the template. Thank you.

Browser other questions tagged

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