I have used django-adaptops for this purpose. i have implemented the mechanism shown in docs. I need to know how can achieve this using browser , for example - i have a template where user has the option to select the csv file, once i click the import button i get the call to my view , but here i cannot read the file to upload to my model. how i can perform this.
this is my template code.
<form action="/manage/dashboard/importProspects" method="post" class="form-horizontal"
enctype="multipart/form-data"> {% csrf_token %}
<div class="row-fluid" style="margin-top: 5%">
<div class="span6">
<div class="control-group">
<p>{{ csvform.fname.label_tag }} {{ csvform.fname }} {{ csvform.fname.url }}</p>
</div>
</div>
<button type="submit" class="btn btn-small btn-success " style="margin-left:10px; ">
Import from CSV
</button>
</div>
</form>
csvForm is form object passed when this template is loaded.
the form code is below:
class ImportCsvForm(forms.Form):
fname = forms.FileField(label='CSV')
and /manage/dashboard/importProspects url will call my view importcsv which right now does not perform anything.
how can i handle this so that i can read the csv file, i cannot get the csvfile path. or am i missing some thing here ? please help.
Follow this,
in template:
<form action="/manage/dashboard/importProspects" method="post" class="form-horizontal"
enctype="multipart/form-data"> {% csrf_token %}
<div class="row-fluid" style="margin-top: 5%">
<div class="span6">
<div class="control-group">
<p>
<input type="file" name="csvfile" />
</p>
</div>
</div>
<input type="submit" class="btn btn-small btn-success " style="margin-left:10px; " />
</div>
</form>
in urls.py:
urlpatterns = patterns("mine.views",
url(r'^', 'csvupload'),)
in views.py file:
def csvupload(request):
if request.method == "POST":
f = request.FILES['csvfile']
with open("/tmp/csvfile.csv", 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
then use csvfile whatever you want.....Hope this helps to you.
Related
HTML form on Django.
I want to perform or create web page in which the button performs the action, and in backend I am handling the Django function.
The code of HTML file is:
<form name="bookappointment" class="form" method="POST">
{% csrf_token %}
<br>
<input type="hidden", name="selecteddoctornumber" value="{{i.doctornumber}}">
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-4">
<button class="btn approve" name="approvebtn">Approved</button>
</div>
<div class="col-md-1"></div>
<div class="col-md-4">
<button class="btn notapprove" name="notapprovebtn">Not Approved</button>
</div>
<br>
</div>
<a class="btn cancel" href="requests">Cancel</a>
<br>
</form>
and the other side the Django function is:
if request.method == 'POST':
if request.POST.get('approvebtn'):
for i in doctor:
if pendingDoctorNumber == i.contactNumber:
i.status = 'Approved'
return redirect('request')
if request.POST.get('notapprovebtn'):
for i in doctor:
if pendingDoctorNumber == i.contactNumber:
i.status = 'Not Approved'
return redirect('request')
but its not working any action just get me back to same page
<form action="{% url 'bookappointment' %}" method="POST">
you have to define bookappointment in your urls.py which redirect to views.py where your function lies with name bookappointment.
I want to select several input files in my flask application, when I want to have an array list of my selected input files, the array is empty. How can I fix that ?
HTML
<form method="POST">
<div class="form-group">
<h6>Select files:</h6> <input type="file" name="inputfiles[]" multiple=""><br><br>
</div>
<div class=" form-group">
<button type="submit" class="btn btn-light text-primary" >GO</button>
</div>
</form>
Python
#app.route('/gp_bagging_several_apps', methods=['POST','GET'])
def gp_bagging_several_apps():
if request.method == 'POST':
print("HELLO")
f = request.files.getlist("inputfiles[]")
print(f)
I also tried with "inputfiles" instead of "insteadfiles[]". I had the same problem.
Thank you
I think in your input tag, you should have multiple. In your form tag, have action and enctype.
You can try something like below:
<form action="{% url 'function' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p><input type="file" name="files" required multiple/></p>
<p><input type="submit" value="Upload" class="btn btn-primary btn-large"/></p>
</form>
And in the function:
if request.method == 'POST':
files = request.FILES.getlist('files')
for file in files:
# process your file
Let me know if it works.
I am new to django.I want to upload two files in single page.I have created form for uploading one file.But with same code I have tried upload two files by making some changes.But I can't get it .
Please help me to submitting two files in one submit button in a single page
views.py
from __future__ import unicode_literals
from django.shortcuts import render
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.conf.urls import url
#import csv
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
#request.FILES['myfile'] and request.FILES["myfile1"]:
myfile = request.FILES['myfile']
#myfile1=request.FILES["myfile1"]
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
#filename1=fs.save(myfile1.name, myfile1)
uploaded_file_url = fs.url(filename)
#uploaded_file_url1 = fs.url(filename1)
#data = [row for row in csv.reader(myfile.read().splitlines())]
return render(request, 'myapp/simple_upload.html', {
'uploaded_file_url': uploaded_file_url,
})
#upload_file = request.FILES['upload_file']
#data = [row for row in csv.reader(upload_file.read().splitlines())]
return render(request, 'myapp/simple_upload.html')
def home(request):
return render(request,'myapp/home.html')
html
<!doctype>
<html>
{% block content %}
<body>
<div class="col-md-12">
<form action="{% url "home" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<label for="fileupload" class="btn btn-primary col-md-2 col-sm-4 uploadBtn" >Upload GSTR 2A</label><br>
<input type="file" class="fileupload" id="fileupload" name="myfile" required="True">
</div>
<div class="col-md-1 col-sm-2" style="text-align:center">
<i class="fa fa-check-circle checkIcon"></i>
</div>
<div class="col-md-1 col-sm-2">
<p class="cancel">X</p>
</div>
</div>
<div class="col-md-12">
<form action="{% url "home" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<label for="fileupload" class="btn btn-primary col-md-2 uploadBtn" >Upload Purchase Account</label><br>
<input type="file" class="fileupload" id="fileupload" name="myfile" required="True" >
<div class="col-md-1">
<a"<p class="cancel">X</p><a>
</div>
</div>
<div class="buttonGroup">
<button type="submit" class="btn btn-primary recBtn">Reconcile</button> <span class="backBtn"> Back</span>
</div>
</form>
</div>
{% endblock %}
</body>
</html>
You only need to have two type file inputs inside the form, and get it in the view exactly like the first you created, like this:
<form method="post" enctype="multipart/form-data" required="True">
{% csrf_token %}
<input type="file" name="myfile">
<input type="file" name="myfile2">
<button type="submit">Upload</button>
</form>
and in your views, you get it and save it like the first one:
myfile = request.FILES['myfile']
myfile2 = request.FILES['myfile2']
In case you need to add the input file outsite the form, you need to add the "form" attribute to the input file. like this:
<input type="file" name="myfile2" form="FORM_ID">
just replace FORM_ID with the id of your form.
In my Django template, {{ form.ietf_tag|bootstrap }} renders as
Django rendering
<div class="form-group">
<label class="control-label " for="id_ietf_tag">IETF tag</label>
<div class=" ">
<input class=" form-control" id="id_ietf_tag" maxlength="12" name="ietf_tag" type="text">
</div>
</div>
I want to insert a <button> before <input>, so I figured I'll just copy, paste, and modify the rendered HTML to where it looks something like this:
Manual rendering
<div class="row">
<div class="col-md-6">
<form action="" method="post">
{% csrf_token %}
<!-- Manually render ietf_tag input -->
<div class="form-group flex {% if form.ietf_tag.errors %}has-error{% endif %}">
<label for="{{ form.ietf_tag.id_for_label }}" class="control-label">{{ form.ietf_tag.label }}</label>
<div class=" ">
<button class="btn btn-primary get-code" data-url="{% url 'ajax_temporary_code' %}">Get Code</button>
<input id="{{ form.ietf_tag.id_for_label }}" class="form-control temp-code required" maxlength="12" name="{{ form.ietf_tag.html_name }}1" type="text" disabled value="{{ form.ietf_tag.value|default:"-" }}">
</div>
<span class="help-block">{{ form.ietf_tag.errors.0 }}</span>
</div>
<!-- -->
{{ form.common_name|bootstrap }}
{{ form.native_name|bootstrap }}
{{ form.direction|bootstrap }}
{{ form.comment|bootstrap }}
<button type="submit" class="btn btn-primary pull-right">Create</button>
</form>
</div>
</div>
The problem
On <form> submission, everything else is submitted except the ietf_tag, which I manually rendered.
QueryDict: {u'common_name': [u''], u'comment': [u''], u'csrfmiddlewaretoken': [u'G6UP5DxrSHHPPQzj6SbxM06Hh8yT9ksm'], u'direction': [u'l'], u'native_name': [u'']}
I double check the name attribute and it was correct. There was no problem using Django-rendered input.
Why is this happening?
Maybe I can accomplish the same result without having to copy, paste, and modify the HTML directly in the template?
EDIT: Put more context in the HTML code
Silly me. The disabled attribute in <input> is what causes the problem. I removed it and now the value is included in the form submission.
Lesson learned
If your <input> is disabled, the value won't be submitted by the form.
This is my first time using Flask and I have created the form for the visitors to fill out, but I want to use the bootstrap formatting so its looks similar to another form I am using in the website. Im not sure how I can link the form together. Here is my code for the contact.html page:
{% extends "index.html" %}
{% block content %}
<div class="content fixed-height">
<h3> {{ title }} </h3>
<!--<form action="http://127.0.0.1:5000/static/contact.php" method="post">
<div class="form-group">
<label>Your Name *</label>
<input type="text" name="cf_name" class="form-control" placeholder="Enter Name" required autofocus/>
</div>
<div class="controls-group">
<label class="control-label"> Your e-mail *</label>
<div class="controls">
<input type="email" name="cf_email" class="form-control" placeholder="Enter Email" required/>
</div>
</div>
<div class="form-group">
<label>Message *</label>
<textarea name="cf_message" class="form-control" placeholder="Enter Message" rows="6" required></textarea>
</div>
<input type="submit" value="Send" class="btn btn-primary">
<input type="reset" value="Clear" class="btn btn-primary">
</form> -->
<form action="{{ url_for('contact') }}" method=post
{{ form.hidden_tag() }}
{{ form.name.label }}
{{ form.name }}
{{ form.email.label }}
{{ form.email }}
{{ form.subject.label }}
{{ form.subject }}
{{ form.message.label }}
{{ form.message }}
{{ form.submit }}
</form>
</div>
{% endblock %}
The first part of the contact.html page is an old form that I was using and is in comment tags. Any help would be much appreciated
I'm guessing you're using the WTF Flask extension for working with forms?
Flask also has a Bootstrap extension that you can install using pip:
pip install flask-bootstrap
You can then import it and into the module that your Flask application instance has been created in:
from flask.ext.bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap(app)
This will provide you with some great functionality including a helper method that you can use to quickly generate forms in your HTML templates.
Go to the page where you want to generate the form and after your extends statement do the following:
{% import "bootstrap/wtf.html" as wtf %} # imports the form template elements
# where you want your form to be
{{ wtf.quick_form(form) }} #the method takes the form argument from your view function
This will generate a form for you. You can read more about the Bootstrap extension here. Go to the Templates page and look for the section of Forms. Good luck!