Reputation: 103
I've been going through the django documentation, but so far everything I've tried hasn't worked for me. I'm trying to make it so if the user enters the url to a certain page and they are not already logged in then they are redirected to the login page that gives them a popup error message that says they don't have access to the page until they have logged in.
Here is a small snippet of code from the views.py
def home(request):
if request.session.test_cookie_worked():
return render(request, 'page/home.html')
else:
return render(request, 'page/login.html')
Everything works except for the error message not popping up if they are redirected to the login page. I've looked at other stack overflow questions that people have asked that are similar to this, but those don't seem to work for me either. Any advice?
Upvotes: 3
Views: 13957
Reputation: 31
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.
Upvotes: 3
Reputation: 33335
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.
Upvotes: 3