I have to accept excel file from user and perform some operation on it using pandas dataframe.
So to load the dataframe using pandas I need to pass the path of file:
fd =pd.read_excel('C:\users\chan\desktop\abc.xlsx')
In django I am trying to use HTML input type file to get the location of file, so that I can pass it in pandas but unable to get file location in python variable.
I tried below code but it's printing data on html page instead of storing it's path in variable:
HTML:
<html>
<head>
<title>Coordinates to Bounding Box</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />
<input type="submit" value="Upload" />
</form>
{% block content %}
<h3>File uploaded successfully</h3>
{{file.name}}
</br>content = {{contentOfFile}}
{% endblock %}
</body>
</html>
Django's views.py
from django.shortcuts import render
from django.conf.urls.static import static
from django.http import HttpResponse
# Create your views here.
def index(request):
if request.method == 'POST':
file1 = request.FILES['file']
contentOfFile = file1.read()
if file1:
return render(request, 'index.html', {'file': file1, 'contentOfFile': contentOfFile})
return render(request,'index.html')
Is there any way I can get the path of excel file or load the excel data in pandas dataframe?
in html you put:
<input type="file" name="excel_file" accept=".xlsx">
then in views.py:
excel_file = request.FILES.get('excel_file')
df = pd.read_excel(excel_file)
Related
home.html
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name = 'img' >
<button type="submit"> Post On Facebook </button>
</form>
views.py
def home(request):
if request.method == 'POST':
# get the image absolute location
return render(request,'home.html')
I want the file path, so that I can upload the file on facebook using GraphAPI.
You need to set your upload path in your models file.
Then you can save it to that particular path in your view function.
For details refer - https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html
Firstly, I am getting a csv file from the user.
(Template file:)
<form method="post" action="{% url 'rowcol' %}" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file" accept=".csv">
<button type="submit">Upload File</button>
</form>
Then i am generating a list of all the columns present in the file and then calling another html file. (views.py:)
def rowcol(request):
if request.method == 'POST':
file = request.FILES['file']
dataset=pd.read_csv(file)
lst=list(dataset)
return render(request, 'Link5_rc.html', {'arr':lst})
return HttpResponse('')
In that html file, i am creating buttons for all the columns present.(Link5_rc.html:)
{% for link in arr %}
<form action=" " method="post">
<button name="{{link}}" type="submit" value="{{link}}">{{link}}</button>
</form>
{% endfor %}
Now the following is the part where i am stuck: I want these buttons to redirect to another html page or maybe a view in views.py , where i can show to the user which column he/she selected and then perform further actions on that particular column.
You can pass one or more values to the request as in the following example:
Some text
You can use variables like:
Some text
In your app urls.py you should set the following to receive the extra data in the request:
url(r'^your_name/(?P<value_1>[\d\D]+)$', views.your_view, name="your_url_alias")
Then, in your view function you should receive the data as in:
def your_view(request, value_1):
An then you can use the value to filter the queryset.
I just need the file path.
This is what I came with so far:
index.html:
<form enctype="multipart/form-data" action="{% url 'polls:search_for_match' %}" method="post">
{% csrf_token %}
<label for="file_path"></label> <input type="file"
class="form-control" id="file_path" name="file_path" >
<button type="submit" class="btn btn-default" >Analyze!</button>
</form>
view.py
def searchMatch(request):
form_class = Query
if request.method == 'POST':
form = form_class(request.POST, request.FILES)
**file = request.FILES['file_path']**
last_restarts = request.POST.get('restarts' , '')
with zipfile.ZipFile(file) as z:
.....
forms.py
class Query(forms.Form):
file_path = forms.FileField()
the problem is in this line: file = request.FILES['file_path'].read()
I don't get the file path, only the file name.
The file path from the client can't possibly be of any use to you. Your server application has no access to arbitrary paths on the client, for obvious security reasons.
File inputs provide the file itself for upload; that's all you can access, and all you should need.
I have a simple Django site and I want to pass data from the first box, and return that value plus 5 to the second form box on the page. I later plan on doing math with that first value but this will get me started. I am having a lot of trouble retrieving the form data. I know I need to create a function in my views.py file to process the form, and I need to put something in URLs.py to retrieve the form data. I have tried everything in tutorials, etc, but can't figure it out.
My html template is a simple page that has a form with two fields and a submit button. Django runserver pulls up the html page just fine. Here is my code:
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django import forms
def index(request):
return render(request, 'brew/index.html')
#Here I want a function that will return my form field name="input",
#and return that value plus 5 to the form laveled name="output".
#I will later us my model to do math on this, but I cant get
#this first part working
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
Here is my html template, index.html:
<html>
<head>
<title>Gravity Calculator</title>
</head>
<body>
<h1>Gravity Calculator</h1>
<p>Enter the gravity below:</p>
<form action="/sendform/" method = "post">
Enter Input: <br>
<input type="text" name="input"><br>
<br>
Your gravity is: <br>
<input type="text" name="output" readonly><br>
<br>
<input type="submit" name="submit" >
</form>
</body>
</html>
You will need to populate the result to context variable which the template can access.
view:
def index(request):
ctx = {}
if request.method == 'POST' and 'input' in request.POST:
ctx['result'] = int(request.POST.get('input', 0)) + 5
return render(request, 'brew/index.html', ctx)
then in your template:
<html>
<head>
<title>Gravity Calculator</title>
</head>
<body>
<h1>Gravity Calculator</h1>
<p>Enter the gravity below:</p>
<form action="/sendform/" method = "post">
Enter Input: <br>
<input type="text" name="input"><br>
<br>
Your gravity is: <br>
<input type="text" name="output" value="{{ result }}" readonly><br>
<br>
<input type="submit" name="submit" >
</form>
</body>
</html>
Looks like you are quite new at Django, I recommend:
use method based views, until you are comfortable with it, then
start using class based views, advantage being code reusability, but ultimately class based views spits out view methods, a good
reference site is ccbv.co.uk
using form class
Python: 2.7.11
Django: 1.9
I want to upload a csv file to Django and analyze it with a Python class. No saving is allowed and the file is only needed to reach the class to be analyzed. I'm using Dropzone.js for the form but I don't understand how I should configure/program the views to achieve this.
<form action="/upload/" method="post" enctype="multipart/form-data" class="dropzone" id="dropzone">
{% csrf_token %}
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
I have found an article about this but it describes saving and is based on Django 1.5.
view.py
def upload(request):
if request.method == 'POST':
file = FileUploadForm(request.POST)
if file.is_valid():
return HttpResponseRedirect('/upload/')
else:
file = FileUploadForm()
return render(request, 'app/upload.html', {'file': file})
forms.py
from django import forms
class FileUploadForm(forms.Form):
file = forms.FileField()
Closing Update:
The most important difference between the helping answer and my situation is that I had to decode my input.
See the following line as mine csv_file in handle_csv_data:
StringIO(content.read().decode('utf-8-sig'))
Access the csv file in the view function. If you are using python 3, you must wrap the InMemoryUploadedFile in a TextIOWrapper to parse it with the csv module.
In this example the csv is parsed and passed back as a list named 'content' that will be displayed as a table.
views.py
import csv
import io # python 3 only
def handle_csv_data(csv_file):
csv_file = io.TextIOWrapper(csv_file) # python 3 only
dialect = csv.Sniffer().sniff(csv_file.read(1024), delimiters=";,")
csv_file.seek(0)
reader = csv.reader(csv_file, dialect)
return list(reader)
def upload_csv(request):
csv_content=[]
if request.method == 'POST':
csv_file = request.FILES['file'].file
csv_content = handle_csv_data(csv_file)
return render(request, 'upload.html', {'content':content})
Your original code did not use django's form framework correctly, so I just dropped that from this example. So you should implement error handling when the uploaded file is invalid or missing.
upload.html
<form action="/upload/"
method="post"
enctype="multipart/form-data"
class="dropzone"
id="dropzone">
{% csrf_token %}
<div class="fallback">
<input name="file" type="file"/>
<input type="submit"/>
</div>
</form>
{% if content %}
<table>
{% for row in content %}
<tr>
{% for col in row %}
<td>{{ col }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% endif %}
I've added a 'submit' button so this works without the dropzone thing. I also removed 'multiple' from the file input, to keep the example simple. Finally there's a table if the template receives content from a parsed csv. But when using dropzone.js, you have to use a javascript callback function to display the table.