python-3.x – Django + Python, show modal using {% if %} in template


I'm checking if there are active groups, if there aren't, you must present a modal and not the registration form, but it is not working:

from django.shortcuts import render, redirect
from django.core.mail import send_mail
from django.template.loader import get_template
from django.conf import settings
from .models import *
from .forms import *
from import email, parentEmail

def create_student(request):
    form = StudentForm(request.POST or None)
    group = Group.objects.filter(active=True).first()
    show_modal = False

    if not group:
        show_modal = True

    if form.is_valid():
        group = Group.objects.filter(active=True).first() = group
        student =
        request.session['student_id'] =
        return redirect('registrations:parent_student')

    return render(request, 'student-form-registration.html', {'form': form})


<!-- Modal Fim Inscrição -->
{% if show_modal is True %}
    <div id="modal" class="modal fade" tabindex="-1" role="dialog" id="inscricaoEncerrada">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-xs-12 col-sm-12 col-md-12">
                            <div class="text-center bottom-border">
                                <img class="img-modal" src="{% static 'images/ilustra3.png' %}" />
                            <p class="text-modal text-center">Olá! As inscrições para a próxima turma da Estação Hack Teens estão encerradas. A próxima turma vai
                                acontecer nos dias 06 e 07 de Outubro, e as inscrições estarão abertas a partir do dia 03
                                de Setembro! Volte nessa data e não deixe de participar :) </p>
                            <div class="text-center">
                                <a data-dismiss="modal" class="btn btn-primary btn-estacao">Voltar para Estação Hack Teens</a>
{% endif %}

I think I don't know how to use the {% if %} in the template, does anyone know how to help me?


The code is ok – but you're not passing the Python show_modal variable to the template.

This has to be done on the line that tells you to render the template (and of course, for each variable you want to use in the template):

return render(
      {'form': form, 'show_modal': show_modal}

Also, it doesn't make much sense to use if ... is True – it would work in this case, but not in many others, and it's uglier than saying "climb up" in Portuguese. The variable's value is already "true" – so just use the variable itself as an if expression:

 {%  if show_modal  %}   

It doesn't need any other comparison – this tip is valid for both the template language, Python code and many other languages.

Scroll to Top