i am getting a 404 error when submitting a form. I try to upload a .png through that form and submit it right after the upload. Then the Server (Python, Flask) should be able to work with that. Does anyone know where my issue is?
AJAX:
<script>
document.getElementById("exampleFormControlFile1").onchange = function() {
console.log("Came here");
$.ajax({
url:'/uploadPNG/',
type:'post',
data:$('#exampleFormControlFile1').serialize(),
success:function(){
console.log("Came here");
}
});
};
</script>
HTML:
<form method="POST" id="form">
<div class="form-group">
<label for="exampleFormControlFile1">Upload your .png template</label>
<input type="file" class="form-control-file" id="exampleFormControlFile1">
</div>
</form>
SERVER:
#app.route('/uploadPNG/', methods=['POST'])
def upload():
if request.method == 'POST':
print("Got png")
return "gotcha"
Thank you in advance
I just figured out the issue. Gonna answer my own post here so that others may have it easier.
A magic wizard once told me to always check the documentation.
http://flask.pocoo.org/docs/1.0/patterns/fileuploads/
Then I had to adjust the AJAX call like here:
'append' called on an object that does not implement interface FormData
And then i had to add the name "file" to the input tag.
Related
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
Inspired from a, b and other sources I am trying to upload a file via a Django Form in the following way:
HTML:
[..]
<script>
$(document).on('change', '.btn-file :file', function() {
document.getElementById("form").submit();
});
</script>
[..]
<form id="form"
method="POST"
action="/licenses/uploadLicense"
enctype="multipart/form-data">
{% csrf_token %}
<span class="btn btn-default btn-file leftMenuButton">
Upload License <input id="filecontent" type="file">
</span>
</form>
[..]
View:
#login_required
def uploadLicense(request):
if request.method == 'POST':
form = UploadLicenseForm(request.POST, request.FILES)
if form.is_valid() :
license = LicenseModel.objects.create()
license.setContent(request.FILES['content'])
license.save()
return redirect(main)
My line form.is_valid() returns false and when debugging inside that method I found the following errors: {'filecontent': [u'This field is required.']}. So for some reason the file is not being uploaded it seems. But how do I go on from here and figure out why?
You haven't given your input element a name attribute, so the browser won't send any data.
I am pretty new to the Flask framework with Miguel Grinberg's Book, Flask Web Development as my reference. For now i have a view function that handles logins and I have no idea how to efficiently implement this using a modal activated by a login button located on the navbar(bootstrap) since this is handled at domain.com/login. The only solution i can think of as deleting this view and copying the code in every view function which i am sure is not a good solution at all.
from .forms import LoginForm
from flask.ext.login import login_user
#auth.route('/login/', methods = ['GET', 'POST'])
def login():
form=LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is not None and user.verify_password(form.password.data):
login_user(user, form.remember_me.data)
flash("login success")
return url_for(".index",username=user.username))
flash("Invalid username or password.")
return render_template('auth/login.html',form=form)
You can use a modal and to the action attribute of the form you pass the route to your handler function /login/. Something like so:
<div class="modal hide" id="myModal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">x</button>
<h3>Login to MyWebsite.com</h3>
</div>
<div class="modal-body">
<form method="post" action='/login/' name="login_form">
<p><input type="text" class="span3" name="eid" id="email" placeholder="Email"></p>
<p><input type="password" class="span3" name="passwd" placeholder="Password"></p>
<p><button type="submit" class="btn btn-primary">Sign in</button>
Forgot Password?
</p>
</form>
</div>
<div class="modal-footer">
New To MyWebsite.com?
Register
</div>
</div>
You could use ajax for this.
For example, your login button has class login-js.
Using jquery you could do something like this:
$('.login-js').click(function(){
$.ajax({
url: '/login/',
type: "POST",
dataType: 'json',
success: function(data) {
if (data.status == 'ok') { //if your response have 'status' key
alert('Logged');
} else {
alert('Error.');
}
}
});
})
But you'll need to change your view to return json response. I'm not confident how to do this using Flask.
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...
I have django 1.4 and I am following a tutorial which uses an older version of django. Its a simple tutorial which creates a wiki app with Page as model.
The problem is that the view function corresponding to a POST method in a form is not getting invoked.
This is the content in the urls.py:
url(r'^wikicamp/(?P<page_name>[^/]+)/edit/$', 'wiki.views.edit_page'),
url(r'^wikicamp/(?P<page_name>[^/]+)/save/$', 'wiki.views.save_page'),
url(r'^wikicamp/(?P<page_name>[^/]+)/$', 'wiki.views.view_page'),
This is the content of the template edit.html:
<from method = "get" action="/wikicamp/{{page_name}}/save/">
{% csrf_token %}
<textarea name = "content" rows="20" cols="60">
{{content}}
</textarea>
<br/>
<input type="submit" value="Save Page"/>
</form>
this is link to save
And this is the content in views.py:
def edit_page(request, page_name):
try:
page = Page.objects.get(pk=page_name)
content = page.content
except Page.DoesNotExist:
content = ""
return render_to_response("edit.html", {"page_name":page_name, "content":content}, context_instance=RequestContext(request))
def save_page(request, page_name):
return HttpResponse("You're looking at the page %s." % page_name)
I initially I was getting csrf related error and I then tried all the fixes provided in https://docs.djangoproject.com/en/dev/ref/contrib/casrf/ and followed many many stackoverflow question related to POST and django. Now nothing happens when I click the 'Save Page' button, nothing! Not even any request being sent from the form (Using firebug to track the HTTP request and response)
You have a typo in your HTML: from instead of form.
You may realize this, but that code won't really save anything. I'm not sure what blog you are following, but you would be better-off following the official Django tutorial in the documentation, then reading the forms docs.
You may need to change method to "POST" in your form.
<from method = "get" action="/wikicamp/{{page_name}}/save/">
to
<form method = "post" action="/wikicamp/{{page_name}}/save/">
There are some spelling mistakes, such as from instead of form.
Also the form is malformed.
Change:
this is link to save
to
<input type="submit" value="Save Page" />
And thirdly, change the method= "get"to method="POST".
The entire form should look like this
<form method = "POST" action="/wikicamp/{{page_name}}/save/">
{% csrf_token %}
<textarea name = "content" rows="20" cols="60">
{{content}}
</textarea>
<br/>
<input type="submit" value="Save Page"/>
</form>
Also what #DanielRoseman said. But hey, it might come further down the road.