How to add alert popup boxes in django? - python

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?

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.

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.

Related

Python Flask wtforms disable form input field if checkbox is ticked

Im struggling to get this to work.
I've got a python flask form that has a check box and an input field. I want to disable the input field if the check box is ticked. I've tried using a script in the HTML template but it doesn't seem to work, so I'm not sure what I'm doing wrong.
<div class="mb-3">
{{ rent_add_form.full_amount_received.label }}
{{ rent_add_form.full_amount_received }}
</div>
<div class="mb-3">
{{ rent_add_form.amount_received.label}}
{{ rent_add_form.amount_received }}
</div>
the full_amount_received is the checkbox, and the amount_received is the input field.
at the bottom of the HTML page I've got the following script
<script>
function myFunction() {
console.log
// Get the checkbox
var checkBox = document.getElementById("full_amount_received");
// If the checkbox is checked, display the output text
if (checkBox.checked == true){
document.getElementById("amount_received").disabled = true;
} else {
document.getElementById("amount_received").disabled = false;
}
}
</script>
if I check in chrome on developer tools, the ID's match up with what I've specified, but the console shows nothing when checking or unchecking the box.
i figured this out, i had to add render_kw={"onclick": "disableTextBox()"} to the properites in the form field within the form.py file

Problem with updating an already updated html dom with Flask

I have a flask dropzone to upload files.
Once an upload is done I want to print a log text on the html site
It works so far, the only problem is - the div tag doesn't update the log text after the second upload. The website stays with the text from the first upload.
index.html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function(){
window.setInterval(function() {
loadNewLogger()
}, 500)
function loadNewLogger(){
$.ajax({
url:"/write_log",
type: "POST",
datatype: "json",
success: function(data){
$(logger).replaceWith(data)
}
});
}
});
</script>
<body>
<div style="color:rgb(0, 0, 0);text-align:center">
CDR PIPELINE </div>
{{ dropzone.create(action='upload') }}
{{ dropzone.load_js() }}
{{ dropzone.config() }}
<div id="logger">
{{ logger }}
</div>
</body>
</html>
logger.html (otherwise I would render index.html twice)
<div id="logger">
{{ logger }}
</div>
excerpt from flask_app.py:
#app.route('/',methods=['POST','GET'])
def upload():
if request.method == 'POST':
f = request.files.get('file')
f.save(os.path.join(app.config['UPLOADED_PATH'],f.filename))
upload.logger = ""
es.main()
upload.logger = es.main.result
return upload.logger
return render_template('index.html')
#app.route('/write_log',methods=['POST'])
def log():
logger = upload.logger
return jsonify('', render_template('logger.html', logger=logger))
Why is it updating the text from upload.logger only once?
First of all, instead of JQuery AJAX, I would recommend using PHP. For example, when you upload files from index.html you can redirect to upload.php, and you can display the message using "echo"
But even if you aren't comfortable with that, don't get too much into Python or JQuery. Your problem can very easily be solved with plain JavaScript:
Here is your html element in logger.html:
<div id="logger"></div>
In flask app.py:
document.getElementById("logger").innerHTML="Your message to be displayed"
I would also recommend you to remove setinterval in index.html as people don't like dynamically reloading blocks

POST vs GET method in Django's view function

My app's urls.py is:
from django.urls import path
from . import views
app_name = 'javascript'
urlpatterns = [
path('create_table', views.create_table, name='create_table')
My views.py is:
def create_table(request):
if request.method == 'POST':
row_data = "this is row data"
context = {'row_data': row_data}
return render(request, 'javascript/create_table.html',context)
My create_table.html is:
{% load static %}
<form action="" method="post">
{% csrf_token %}
<button id="create_table">Get data</button>
</form>
<div id="place_for_table"></div>
<script type="text/javascript">
var row_data = "{{ row_data }}"
</script>
<script src="{% static 'javascript/scripts/create_table.js' %}"></script>
And my create_table.js is:
function create_table() {
document.getElementById("place_for_table").innerHTML = row_data;
}
document.getElementById("create_table").onclick = function() {
create_table()
}
What I want to achieve is: when the /create table URL is requested, only the button is displayed. When the button is pressed, row_data variable's value is displayed below the button.
At this moment the data is displayed for a blink of an eye and then disappears.
I guess I am not distinguishing between POST and GET methods correctly in the view function. Also I have based my logic on the assumption that URL is requested using GET method by default. However if I put a print(request.method) at the beginning of my view, it prints POST.
Also, whenever I load the page for the first time or refresh it, I get a Firefox warning:"To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier."
Other things I tried was to use class-based view with post and get defs or put the create_table's URL in button formaction= tag, but that doesn't help.
I would be thankful for any suggestions on how to achieve this.
The problem might be because when you are submitting the form it refreshes/reloads your page i.e. /create_table url because of which row_data resets
This Might help you to understand why the button submits even though you didn't explicitly provided type="submit" to the button inside your form.
Our aim will be to prevent the event to occur. It can be done using a simple return false statement in our onclick listener as given below:
function create_table() {
document.getElementById("place_for_table").innerHTML = row_data;
}
document.getElementById("create_table").onclick = function(event) {
create_table();
return false;
}

django and dropzone how to post form

I have gone through django and dropzone. I have implemented drag and drop feature of dropzone in django.
My template look like:
<form id="add-multiple" class="dropzone" action="{% url "name_add" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
</form>
<button id="submit-all" type="submit" value="Submit" form="add-multiple">
Submit all files
</button>
<script src="{% static 'js/dropzone.js' %}"></script>
<script type="text/javascript">
Dropzone.options.myDropzone = {
// Prevents Dropzone from uploading dropped files immediately
autoProcessQueue : false,
paramName: "files",
init : function() {
var submitButton = document.querySelector("#submit-all")
myDropzone = this;
submitButton.addEventListener("click", function() {
myDropzone.processQueue();
// Tell Dropzone to process all queued files.
});
// You might want to show the submit button only when
// files are dropped here:
this.on("addedfile", function() {
// Show submit button here and/or inform user to click it.
});
}
};
</script>
Here, I am getting the css and uploading perfectly, but when I submit the form, it doesn't call the {% url "name_add" %} url. I mean, the form is not posted and it doesn't call that url.
I followed this tutorial https://amatellanes.wordpress.com/2013/11/05/dropzonejs-django-how-to-build-a-file-upload-form/ to achieve this.
First thing, my form is not being posted or it says it is not calling the url in form action. Second there is not any use of my form that I have created in forms.py to upload a file. In the tutorial also there is no use of form. Why is that and without form how form can be submitted because view requires form.
Can anyone help me?
in:
Dropzone.options.myDropzone = {
....
actually myDropzone is the camelized version of the HTML element's ID.
so the form id must be my_dropzone instead of add-multiple:
<form id="my_dropzone" class="dropzone" action...

Django request.is_ajax() returns false

This question is not new, however I've spent really plenty of time, but coudn't fixed it.
<form id="test_data_form" action={% url 'insert_test_data' %} method="post">{% csrf_token %}
<input type="submit" value="Insert test data">
<div id="message"></div>
</form>
<script type="text/javascript">
var form = $("test_data_form");
$(document).ready(function() {
form.submit(function() {
$.ajax({
data: form.serialize(),
url: form.attr('action'),
cache: false,
type: form.attr('method'),
dataType:'json',
success: function(response) {
alert("1");
},
error: function() {
alert('Error!');
}
}
);
return false;
}
);
}
);
</script>
views.py
#csrf_exempt
def insert_test_data(request):
print request.is_ajax()
data = {'success': True, 'html': "text"}
return HttpResponse(json.dumps(data), mimetype="application/json")
urls.py
url(r'^hello/insert_test_data/$', insert_test_data, name="insert_test_data"),
Firstly, I've found that success isn't caught, so then while debugging I found that django doesn't think it is an ajax request and redirects me to the different page: /insert_test_data. And I want to stay on the home page.
I've found a lot of advices about that problem (e.g. cache: false) but none of them helped. I agree, that I miss something obvious, but couldn't figure out what exactly.
I'll be realy glad for any help.
The JavaScript to handle the form submit looks ok at first inspection, but there's one mistake:
var form = $("test_data_form");
If you use Firebug or Chrome developer tools and query for this element in the console, you won't get anything back because you're missing a selector (tag, id, class, etc). From your form tag, I think you meant to select by id:
var form = $("#test_data_form");

Categories