Currently working on a Django project where I am stuck in a situation and the scenario is something like that I have two forms in my abc.html page, one is used for input file and second is used to run python script internally. But the issue is even if I don't input the file the submit button "run python script" start's working without submitting a file. Here I want to create a check that submit button "run python script" will run only at one condition when file will submitted otherwise button will disable. It will active only at one condition when user will input the file.
I am sharing the details:
abc.html:
<!--form to input file -->
<form method="post" enctype="multipart/form-data" name="myform">
{% csrf_token %}
<input type="file" id="file" name="doc" class="inputfile" onchange="document.myform.submit()"> </form>
<-- end of input file-->
<!-- form to run python script -->
<form action = "/results/" method="post" id="subform">
{% csrf_token %}
<input type="submit" id="btnSubmit" name="doc" value="run python script" class="btn btn-warning btn-sm" />
</form>
<-- end of form running python script -->
views.py:
def compliance_check(request): #function to upload file
global uploaded_file
if request.method == 'POST':
uploaded_file = request.FILES['doc']
print(uploaded_file.name)
print(uploaded_file.size)
fs = FileSystemStorage()
fs.save(uploaded_file.name, uploaded_file)
messages.info(request, 'your file ' + uploaded_file.name + " has been uploaded successfully")
return render(request, 'enroll/abc.html')
def results(request): #function to run python script
user_id = request.session['user_id']
hash_id, id_exists = compliance(user_id)
request.session['hash_id'] = hash_id
if id_exists:
messages.info(request, "This File has already been analyzed")
return redirect(tables_view)
I have tried multiple ways to create a check but not succeed yet. I hope that everyone will understand the question and the scenario is simple that there should be a check before clicking on run script button that please select the file first. The button should run only at one condition if user upload file.
Related
I wrote an HTML template to send an email using Flask. In the HTML script, I have a form that has a "send" button and once it's clicked, it triggers an email in Flask.
HTML Script
<form class="form-container" action="{{ url_for('send_email') }}">
<div class="form-group">
<label for="to-address">To </label>
<input id= "to-address" name="to-address" type="email"
placeholder="sample#email.com" class="form-input">
</div>
<div class="form-group">
<label for="title">Title</label>
<input id= "email-title" name="email-title" type="text" placeholder="Title"
class="form-input">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea id= "email-body" name="email-body" placeholder="Send Message" class="form-
text-area"></textarea>
</div>
<button id="email-send-btn" type ="submit" class="btn btn-primary"> Send </button>
</form>
FLASK
#application.route('/send_email')
def send_email():
to_address = request.args.get('to-address')
subject = request.args.get('email-title')
text = request.args.get('email-body')
msg= Message(
subject,
sender="abc#email.com",
recipients=to_address,
)
msg.html = render_template("email.html", text=text)
mail.send(msg)
return("success")
The email itself is working well but I have an issue with redirecting the page after clicking the "Send" button. Once I click on the Send button, whose id="email-send-btn", I want to stay in the current page, probably showing a notification popup to indicate the email has been sent successfully. I put return('success)` in the last line of my Flask script, because I had to return something to avoid a blank page.
I tried this following to stay in the same page after hitting the Send button. It allows me to stay in the same page, but also blocks the action completely and doesn't send any email. Is there any way to stay in the same page after clicking the send button without blocking the action of sending email?
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return true;
});
});
Historically returning false from a submit handler prevented form submission without needing to call submit event object methods such as preventDefault and/or stopPropagation
With careful reading you may be able to infer that jQuery documentation says the same thing:
If you'd like to prevent forms from being submitted unless a flag variable is set ... [return the value of the flag from the submit handler added using the jQuery .submit(handler) syntax]
means that if the flag variable is set true, form submission is not prevented.
Hence return false instead of true to stay on the page, letting jQuery handle cross browser compatibility issues.
You can use render template + flash message.
https://flask.palletsprojects.com/en/2.2.x/tutorial/templates/
https://flask.palletsprojects.com/en/2.2.x/patterns/flashing/
from flask import render_template, flash
... your code here ...
flash('Email has been sent successfully.')
return render_template('yourtemplate.html')
And in your template you have to put this code, like in documentation:
% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
Of course you can use any HTML tag instead of unordered list with items.
Right now you just use another callback that does something when the form submits but you don't block the standard submitting. In order to achieve that you should managed the event defining that he should "prevent default" actions.
$form.submit(function(e){ //< add here "e" parameter
e.preventDefault(); //< add this
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false; //< change this
});
I'm trying to submit an image file using javascript onChange, the thing is I don't know the value of the submitted POST form, and how can I set a custom POST value. Here is a simple example:
HTML:
<form id="form" action="upload.php" method="post">
<input type="file" id="file" name="image">
</form>
Javascript:
document.getElementById("file").onchange = function() {
document.getElementById("form").submit();
}
So after I submit the form I can only get the value $_POST['image']. Usually when receiving POST I check for the value of the submit button which I create uniquely for each form such as, updateform, updateclient. Now I want to do the same by creating custom messages, one page will send 'uploadclientimage' the other will say 'uploadshopimage' and so on. This way the upload.php file can process the status to decide what to do next.
In upload.php I want to do like this:
if(isset($_POST['uploadclientimage']))
{//Save in client uploads folder and update client info}
else if(isset($_POST['uploadshopimage']))
{//Save in shops uploads folder and update shop info}
else header("Location: login.php");
using submit button does that easily <input type="submit" name="uploadclientimage">
How can I do something like that with onChange form submit???
Just add a hidden field in the form. For example:
<input type="hidden" name="uploadclientimage" value="">
I want to store/copy file into folder using JavaScript. file is getting from input type file. .
JavaScript Code -
function submitForm(action)
{
// here I want to do copy file into folder
}
HTML Code-
<form id="exampleForm" method="post" action="" enctype="multipart/form-data" >
<input type="file" class="upload" name="imagename" id="imagename" />
<input type="button" name="save_exit" id="save_exit" onclick="submitForm('add_question_sql.php')" value="Save & Exit" />
</form>
I can not use Submit button for some reason.
So how can I copy a file into folder using JavaScript ?
As commented by Paulo, this is not a JavaScript topic. On selection of a file and submission of the form, your server-side application will receive the request and will be in a position to receive the uploaded file and store it somewhere on your server.
Since javascript is Client-side language . so its not possible using javascript.
U have to use any backend technology. like php, java, node.
I just created a django form using this following documentation:https://docs.djangoproject.com/en/1.8/topics/forms/
My Forms.py is similar to this:
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
My Html template is similar to this (from django doc):
<dialog id="addForm">
<form action="{% url "listing" %}" method="post" >
{% csrf_token %}
{{ form }}
<input id="task_submit" type="submit" value="Submit"/>
</form>
</dialog>
<button onlick="PopUp()">Add Listing </button>
<script>
function PopUp(){
document.getElementByID("addForm").showModal();
}
</script>
However, I want my form to be a pop up dialogue when a user clicks on a button called "add tasks". I do not want the form to show until the user clicks a button called "add tasks". I have not been able to find any methods so far to do so while using Django Forms.
Question: How do I implement a pop up dialogue to display my current django form when a user clicks on a button?
Found the solution I was looking for here:
http://blog.raventools.com/create-a-modal-dialog-using-css-and-javascript/
I'm just getting started with adding a backend into my front-end code and think flask is a good framework to start learning with.
One of the things I'm having trouble with is submitting information to the server for processing. Specifically here I have a list of radio buttons, and I want to send to a server a list of all the radio buttons the user checked when he or she hit submit. The server then processes that information and returns a new page.
This is the form:
<form action="{{ url_for('timeline') }}" method="post">
{% for each_tag in tags %}
<div class="checkbox">
<label>
<input type="checkbox" name="channel[]" value="{{each}}" >
{{each_tag}}
</label>
</div>
{% endfor %}
<button type="submit"> submit </button>
</form>
Here are the relevant functions in the main flask file:
#app.route('/')
#app.route('/index.html')
def checklist():
for rownum in range(1,sh.nrows):
row_values = sh.row_values(rownum)
all_tags.add(row_values[7])
return render_template('index.html', tags=all_tags)
#app.route('/timeline.html', methods=['POST','GET'])
def timeline(request):
//do stuff with list of checked radio buttons
return render_template('timeline.html')
I'm not exactly sure how information is passed back and forth. I can send server info to the html templates and I think once I get this example down and figure out how information is passed the other direction I can start doing some interesting things. =)
Naming the checkboxes with trailing square brackets ("channel[]") is a PHP thing, Flask doesn't need that.
Just use the same name in all the checkboxes:
<form action="{{ url_for('timeline') }}" method="post">
{% for each_tag in tags %}
<input type="checkbox" name="channel" value="{{each}}" >
{% endfor %}
<button type="submit"> submit </button>
</form>
Then to retrieve the array of selected values use request.form.getlist():
#app.route('/timeline.html', methods=['POST','GET'])
def timeline(request):
checked = request.form.getlist('channel')
# do something with checked array
return render_template('timeline.html')