Upload 2 files from 2 inputs with Flask - html

I need to have 2 buttons for uploading 2 different files by using Flask, but I cannot find the way to do that.
The answer that I found several times was to add "multiple" in parameters, but this is not what I want because I need to have a button for each file.
In my form I need the onchange="form.submit() parameter, and I want to have others entries.
The files I have tu upload are excel files
upload.html :
<form method="POST" enctype="multipart/form-data">
<div class="input-field">
<input type="text" name="other_input" onchange="form.submit()" id="other_input">
<label>Other Input</label>
</div>
<div class="div_files">
<label class="Button"> Select File 1</label>
<input name="1st_file" type="file" onchange="form.submit()" value="1st_file">
<label class="Button"> Select File 2</label>
<input name="2nd_file" type="file" onchange="form.submit()" value="2nd_file">
</div>
<input type="submit" value="Show result" action="other" id="btns">
</form>
app.py :
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/index, methods=['POST', 'GET'])')
def index():
file1 = request.files["1st_file"]
file2 = request.files["2nd_file"]
return render_template('other_page.html', variable1=file1, variable2=file2)
I tried to use 2 different forms to get what I want, but it didn't work either
Thank you for your help :)

Related

Django not printing post request

I'm learning Django and creating my website...
Created and basic HTML contact form and to check if it is working I've added an print option on form submission(method==post) but
after I submit the form, on terminal prints nothing
below are my codes
Thank you For your time
views.py
def contact(request):
if request.method == 'POST':
print ("we are done")
return render(request,"news/Home/Homepage.html")
_____models.py_______
class Contact(models.Model):
name=models.CharField(max_length=100)
email=models.CharField(max_length=150)
msg=models.TextField()
____my html contact form__________
<form class="grid-form" method="post" action="/">
{% csrf_token %}
<div class="form-control narrow">
<label for="name">Name</label>
<input name="name" id="name" type="text">
</div>
<div class="form-control narrow">
<label for="email">Email</label>
<input name="email" id="email" type="email">
</div>
<div class="form-control">
<label for="message">Message</label>
<textarea name="message" id="message" rows="4"></textarea>
</div>
<ul class="actions">
<li><input value="Send Message" type="submit"></li>
</ul>
</form>
urls.py
from . import views
urlpatterns = [
path("" , views.index),
path("league",views.index2),
path("pl",views.index3),
path("ptable", views.index4),
path("fs", views.index5),
path("latest", views.index6),
path("history", views.index7)
]
Give path in your action in the form:
<form class="grid-form" method="post" action="/">
There, should be action attribute should correspond to the path which will trigger contact function in views.py.
EDIT
Your urls.py does not contain any url where you could send the request from form. As, I already mentioned about the action, your home directory is not in index function. So, you have to add a path to send request. Like:
from . import views
urlpatterns = [
path("" , views.index),
path("contact" , views.contact, name="contact"), # Here
path("league",views.index2),
path("pl",views.index3),
path("ptable", views.index4),
path("fs", views.index5),
path("latest", views.index6),
path("history", views.index7)
]
And, you have to send the form to that path www.example.com/contact. Like:
<form class="grid-form" method="post" action="{% url 'contact' %}">
*Note:- I gave the action value according to the name, which is great practice. So, lets start giving name in the url. But, the way you did is also fine.

How I save data on database table from django?

I made a django website where doctor and patient both can signup. Patient mark their problem and it will send to those doctor whom he/she want, like question asking on Quora. And I also want to save data in db
But my webpage when patient insert data it does not save in database.
Models.py
class patients(models.Model):
fever=models.BooleanField()
others=models.TextField()
Views.py
from django.shortcuts import render, redirect
from .models import patients
def patient(request):
if request.method == 'POST':
fever=request.POST['fever']
others=request.POST['others']
patient_details=patients(fever= fever,others = others)
patient_details.save()
return render(request, "patient")
else:
return render(request, "patient.html")
Patient.html
<form action="patient">
<label for="exampleFormControlTextarea1"><u>Mark Your Problems</u></label><br>
<!-- FEVER -->
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="inlineCheckbox1" value="option1">
<label class="form-check-label" name="fever" for="inlineCheckbox1">Fever </label>
</div>
<!--Others-->
<h6 style="text-align:left;"><u>Others</u></h5>
<div class="form-group">
<textarea class="form-control" name="others" id="exampleFormControlTextarea1" rows="1"></textarea>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit"> SUBMIT </button>
</h6>
</form>
How I store these data on database ?
try this line
patient_details=patients.objects.create(Fever= fever, others = others)
instead of :
patient_details=patients(Fever= fever, others = others)

flask multiple submit button

I am using flask and jinja2 to create a simple web app to serve up a simple sklearn algorithm for predictions.
In my html I need to get 4 variables: client id, textid, textid1, textid2
It currently works when I have it all connected to one submit button. But I would like to have two submit buttons to have the client id submit at the top of the page and the textid stuff at the bottom of the page. When I try to have two submit buttons it causes the page to refresh and I not able to connect the client id to the 3 textid vars.
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST">
<input name="text", id='text', placeholder="Client ID #", value="{{ client_id|round|int }}" >
<br>
<label>Enter 3 suggestions</label>
<br>
<input name="textid", placeholder="Suggested Model ID #", value="{{ request.form['textid'] }}"/>
<input name="textid1", placeholder="Suggested Model ID #", value="{{ request.form['textid1'] }}"/>
<input name="textid2", placeholder="Suggested Model ID #", value="{{ request.form['textid2'] }}"/>
<input type="submit" >
</form>
</div>
I'm simply grabbing it in flask like this:
#app.route('/suggestion', methods=['GET', 'POST'])
def with_suggestions():
try:
client_id=request.form['text']
except:
#custom function when client id is not entered to get random one
client_id = recommender.random_client_id()
try:
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
#other functional code after this
How can I break up the html to get two submit buttons? Thanks!!
Now that you have updated your code, all you need to do is add hidden inputs to identify where the click was originated from. Also Remove the leading slash from your url_for like I did below
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST" action={{url_for('suggestion')}}>
<input name="text", id='text', placeholder="Client ID" >
<input type="hidden" name="btn_identifier" value="client_id_identifier" />
<input type="submit" >
</form>
<form method="POST" action={{url_for('suggestion')}}>
<input name="textid", id='text', placeholder="Textid1">
<input name="textid1", id='text', placeholder="textid2 ">
<input name="textid2", id='text', placeholder="Textid3">
<input type="hidden" name="btn_identifier" value="text_id_identifier" />
<input type="submit" value="Submit">
</form>
main.py
from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)
#app.route('/suggestion', methods=['GET', 'POST'])
def with_suggestions():
if request.methods == 'POST':
if request.form['btn_identifier'] == 'client_id_btn':
try:
client_id=request.form['text']
except:
# I think this would go in the second elif statement
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
elif request.form['btn_identifer'] == 'text_id_btn':
# run some code to handle a click that was originated from the second button
return render_template('index.html')
if __name__ == '__main__':
app.run()
I made some changes to your code.
index.html
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST" action={{url_for('suggestion')}}>
<input name="text", id='text', placeholder="Client ID" >
<input type="submit" >
</form>
<form method="POST" action={{url_for('suggestion')}}>
<input name="textid", id='text', placeholder="Textid1">
<input name="textid1", id='text', placeholder="textid2 ">
<input name="textid2", id='text', placeholder="Textid3">
<input type="submit" value="Submit">
</form>
</div>
main.py
from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)
#app.route('/suggestion', methods=['GET', 'POST'])
def suggestion():
if request.method == 'POST':
try:
client_id=request.form['text']
except:
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
return render_template('index.html')
if __name__ == '__main__':
app.run()
Note: Values are store in the variable, print to see
I have simplified the process of fetching the info from multiple buttons. Do note that you require the python flask framework for the "request" method.
home.html
<div class="container mt-5">
<div class="row col-4">
<form method="POST" class="form-register">
<input type="submit" name="submit_button" value="Add Email">
<input type="submit" name="submit_button" value="Clear Recipients">
</form>
</div>
</div>
run.py
if request.method == 'POST':
if request.form['submit_button'] == 'Add Email':
print("add email")
elif request.form['submit_button'] == 'Clear Recipients':
print("clear recipients")
you may refer to the link provided for more example
https://www.codegrepper.com/code-examples/python/checking+if+button+pressed+flask

How to trigger a function with checkbox django

I wanna know how I run certain functions depending on the selected checkboxes. This is my visual template:
and this is the code I have for my template is called admin.html:
<div class="panel-body">
<p><button type="button" class="btn btn-black"><i class="fa fa-upload" </i> <span class="bold">IMPORT ALL</span></button> </p>
<p> Import selected reports:</p>
<p> <label><input type="checkbox" value=""> Cisco Backlog Report</label></p>
<p> <label><input type="checkbox" value=""> Planning & Standard</label></p>
<p> <label><input type="checkbox" value=""> Emo Trans Report</label></p>
<p> <label><input type="checkbox" value=""> Phyllis Report</label></p>
<p> <label><input type="checkbox" value=""> Purchase Order View</label></p>
<p> <label><input type="checkbox" value=""> On Hand Inventory</label></p>
<p> <label><input type="checkbox" value=""> Bill of Material</label></p>
<p> <label><input type="checkbox" value=""> Aged</label></p>
<p> <label><input type="checkbox" value=""> Shipment with Times</label></p>
<p><button type="button" class="btn btn-danger">Import</button> </p>
As I mentioned before, I got 10 functions that read several .csv reports and upload the data into models and I trigger them with the URL section. In my views.py I will show two examples:
def importpurchase(request)
Log logic here
def importcisco(request)
Log logic here
def importall(request) # this function is to import all
importpurchase(None)
importcisco(None)
You can receive list of selected checkboxes using request.POST.getlist('mycheckboxname'), you should give your checkboxes name and value accordingly to selected field ('Aged' for example):
<input type="checkbox" name="mycheckboxname" value="Aged">
Then you can call any function depending on what selected in list:
def func1(l,vals):
process_values_in_different_way(l, vals)...
def func2(l,vals):
process_values(l, vals)...
def MyView(request):
values=get_values_from_somewhere()
mylist=request.POST.getlist('mycheckboxname')
if 'Aged' in mylist:
func2(mylist, values)
elif anotherValue in mylist:
func2(mylist, values)
elif...
etc
EDIT(on your comments):
This is how django works: your client send request and you return response. This is called HTTP protocol. When IMPORT button is clicked your client send a form which contains all data entered by the user to the server. This data appears as a part of request object in your view. You can retrieve this data and you can do everything you want with this data. In my example process_values can, for example, select all 'Phyllis Report' objects and return them to response, as part of rendered template. There is no other way how you can do it. You cant just call on click function from server without request. To accomplish what you want you can try to split your logic and put part of it to javascript. You will be able to bound onclick listener to your button and then send requests through ajax to server. But this is a whole new story.
This might be useful: ajax and django

How to upload an image from client side form to Google cloud storage bucket?

There is a form that uploads an image. Now I want to store it in Google cloud storage and get back to print on page. The form is : -
<form action="http://master-engine-799.appspot.com/uploadimage" method="POST" enctype="multipart/form-data">
Upload File: <input type="file" name="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
and the .py file is
import webapp2
import logging
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
class UploadImageHandler(webapp2.RequestHandler):
def post(self):
# code that will upload the image to my bucket on cloud storage
upload_url = blobstore.create_upload_url('/upload',gs_bucket_name='userimagebucket')
class UploadImageHandler(webapp2.RequestHandler):
# code to show uploaded image in bucket
app = webapp2.WSGIApplication([('/uploadimage', UploadImageHandler)],
debug=True)
The upload_url provided by create_upload_url is the URL you want to use as the "action" on the form itself, rather than /uploadimage. So your HTML form should look more like:
<form action="CONTENTS_OF_UPLOAD_URL_HERE" method="POST" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
Your upload handler can then redirect the user to the page showing the results. Example:
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file') # 'file' is file upload field in the form
blob_info = upload_files[0]
self.redirect('/serve/%s' % blob_info.key())
from __future__ import with_statement
import cloudstorage as gcs
import webapp2
import logging
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
def CreateFile(filename,imageFile):
with gcs.open(filename, 'w', content_type = 'image/jpeg') as f:
f.write(imageFile)
f.close()
blobstore_filename = '/gs' + filename
return blobstore.create_gs_key(blobstore_filename)
class MyImageHandler(webapp2.RequestHandler):
def post(self):
bucket='yourbucketname'
imageFile = self.request.get('file')
naemofFile=self.request.get('filename1')
fileName='/yourbucketname'+'/'+naemofFile
blob_key = CreateFile(fileName,imageFile)
logging.info("Blob-Key "+blob_key)
imageUrl = 'https://%(bucket)s.storage.googleapis.com/%(file)s' % {'bucket':bucket, 'file':naemofFile}
app = webapp2.WSGIApplication([('/myimagehandler', MyImageHandler)],
debug=True)
and the form is like this
<html>
<body>
<form action="http://your-app-id.appspot.com/myimagehandler" method="POST" enctype="multipart/form-data">
<input type="file" name="file"><br>
File Name : <input type="text" name="filename1"> <input type="submit" name="submit" value="Submit"> </form>
</body>
</html>