[Django]-How to add alert popup boxes in django?

3👍

Here’s how I’m doing it.

First, if the view code determines that the popup should be displayed, call render() with a named flag in the context:

return render(request, 'page/home.html', {'some_flag': True})

Then, in your page template, if the flag is set, display a <div> element:

{% if some_flag %}
    <div id="some_flag" title="Some Flag">
        <p>Some Text Here</p>
    </div>
{% endif %}

Also in the page template, in the <head> section, create a JavaScript function to display the <div> as a popup dialog:

<head>
    <script type="text/javascript">
        $(document).ready(function() {
            $(function() {
                $( "#some_flag" ).dialog({
                    modal: true,
                    closeOnEscape: false,
                    dialogClass: "no-close",
                    resizable: false,
                    draggable: false,
                    width: 600,
                    buttons: [
                        {
                            text: "OK",
                            click: function() {
                            $( this ).dialog( "close" );
                            }
                        }
                    ]
                });
            });
        });
    </script>
</head>

This solution also requires that you use the jQuery library.

I’m sure there are drawbacks to doing it this way, but it works for me.

3👍

We can pass a variable in context object like a flag.

return render(request, 'index.html', {'alert_flag': True})

and then in templates simply do a check for the alert_flag.

{% if alert_flag %}
    <script>alert("Some Message.")</script>  
{% endif %}

Here no jQuery code is required and I am using native alert.

Leave a comment