Unknown code being added to HTML template when running local server - python

I was building a profile picture feature, it was working fine so I left it for a while, probably a week. I came back to it and ran the local server, but when I do there's a few lines that appear in the console. But do not exist on the source file.
Source file:
<script type='text/javascript'>
Dropzone.options.myDropzone = {
autoProcessQueue : false,
paramName: 'uploaded_image',
dictDefaultMessage: "Drag and drop files or click here to upload picture",
init: function() {
var submitButton = document.querySelector("#submitBtn")
myDropzone = this;
submitButton.addEventListener("click", function() {
myDropzone.processQueue();
});
// Automatically overwrites file so the user can only upload one
this.on("addedfile", function() {
document.getElementById('submitBtn').style.visibility = "visible";
});
this.on('addedfile', function(){
if (this.files[1]!=null){
this.removeFile(this.files[0]);
}
});
}
};
</script>
<!-- Modal -->
<div id="picModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close"></span>
<form action="{% url 'profile_test' %}" method='POST' enctype="multipart/form-data" class="dropzone" id="my-dropzone">{% csrf_token %}
<!-- submit button stays hidden by default, until user selects a picture -->
<button id='submitBtn' type='submit' class='pic-submit-button' style='visibility: hidden;'> Submit </button>
<input id='submit-all' type='file' name='uploaded_image'/>
{{form}}
</form>
</div>
</div>
Now the code I'm seeing when I run the server is only a few lines, and it's in the HTML that creates the modal:
<!-- Modal -->
<div id="picModal" class="modal" style="display: block;">
<!-- Modal content -->
<div class="modal-content">
<span class="close"></span>
<form action="/api/profile_test/" method="POST" enctype="multipart/form-data" class="dropzone dz-clickable" id="my-dropzone"><input type="hidden" name="csrfmiddlewaretoken" value="WDMihPq0zDhDQGaWxSFYyvxjtmxUxsBMpAzcDqVxDGUZj11O8wtqbCfCie1m81Tf">
<!-- submit button stays hidden by default, until user selects a picture -->
<button id="submitBtn" type="submit" class="pic-submit-button" style="visibility: hidden;"> Submit </button>
*****<input id="submit-all" type="file" name="uploaded_image">
<label for="id_user">User:</label><select name="user" id="id_user">
<option value="" selected="">---------</option>
<option value="2">Brian</option>
<option value="3">Charles</option>
</select>
<label for="id_img">Img:</label><input type="file" name="img" required="" id="id_img">
<div class="dz-default dz-message"><span>Drag and drop files or click here to upload picture</span></div></form>
</div>
</div>*****
The last chunk of code I put stars around is the code that is unknown to me. The Django project I cloned was using gulp, I talked to my friends and they said that it may have something to do with it, maybe it's doing something with Dropzone.js?. But why would it inject a random dropdown menu listing users in Django? I didn't use gulp myself because I just wanted to develop the feature, but that may have been a mistake.

Possibly the
{{form}}
is causing this issue.

Related

Add multiple checkout buttons for multiple events on same page Eventbrite

How to add multiple checkout buttons for multiple events on the same page?
<script src="https://www.eventbrite.com/static/widgets/eb_widgets.js"></script>
<script type="text/javascript">
var exampleCallback = function () {
console.log('Order complete!');
};
var getEventID = function(){
var value = document.getElementById('eventID').value;
return value;
};
window.EBWidgets.createWidget({
widgetType: 'checkout',
eventId: getEventID,
modal: true,
modalTriggerElementId: 'checkout_btn',
onOrderComplete: exampleCallback,
});
</script>
HTML Here
{% for event in data.events %}
<form id="form_id">
{% csrf_token%}
<div class="center">
<div class="w3-card-4" style="width:100%;">
<header class="w3-container w3-blue" >
<h1>{{event.name.text}}</h1>
</header>
<div class="w3-container" style="background-color: #ddd;">
<p>{{event.description.text}}</p>
Event ID: <input type="hidden" id="eventID" name="eventID" value="{{event.id}}"><br>
Capcity: {{event.capacity}}
<button id="checkout_btn" class="button" type="button">Buy Tickets!</button>
</div>
</div>
</form>
{% endfor %}
I am showing multiple events in Django and trying to fetch the event id in script code. It works for one event when I provide a hardcoded value.
Any help will be appreciated!
Found the solution, but don't know if it is a good one or not (But working for me):
{% for event in data.events %}
<form id="form_id">
<!-- checkout widget START-->
<script src="https://www.eventbrite.com/static/widgets/eb_widgets.js"></script>
<script type="text/javascript">
var exampleCallback = function () {
console.log('Order complete!');
};
window.EBWidgets.createWidget({
widgetType: 'checkout',
eventId: '{{event.id}}',
modal: true,
modalTriggerElementId: 'checkout_btn-{{event.id}}',
onOrderComplete: exampleCallback,
});
</script>
<!-- checkout widget END -->
{% csrf_token%}
<div class="center">
<header class="w3-container w3-blue">
<h1>{{event.name.text}}</h1>
</header>
<p>{{event.description.text}}</p>
Event ID: <input type="hidden" id="eventID" name="eventID" value="{{event.id}}">{{event.id}}
<br>
Capcity: {{event.capacity}}
<br>
Starting: {{event.start.local}}
<br>
Ending: {{event.end.local}}
</div>
<button id="checkout_btn-{{event.id}}" class="button" type="button">Buy Tickets!</button>
</form>
{% endfor %}
Took the script inside the loop and provided a unique id to the button as checkout_btn-{{event.id}}. It will become checkout_btn-xxxxxxxxxxx121(event ID retrieve from {{event.id}}). Similarly provide the same button id in the script as modalTriggerElementId: 'checkout_btn-{{event.id}}',
and provided eventId: '{{event.id}}', in place of eventId: getEventID. Now it can distinguish between each event.

Python Flask - Make uploaded "file chosen" name stick on the HTML page

I have two input buttons. One is for uploading a file, and the other one is a submit button that adds the uploaded file to the database.
My problem is, after I submit the file, the first button that's used for uploading goes back to "No file chosen" next to the button. However, I want the uploaded file name to "stick" to the UI/html page as the file chosen.
Here is my File class:
class Files(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, unique=True, nullable=False)
data = db.Column(db.LargeBinary)
Here is my HTML code:
<td>
<form class="" action="{{url_for('main.upload_file')}}" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="{{row.id}}">
<input style="margin-bottom: 5px;" type="file" accept=".csv" name="csvfile" id="upload" value ="{{row.name}}"> <br>
<input style="margin-bottom: 10px;" type="submit" name="" value="Submit"> <br>
</form>
<a href={{ url_for('main.files') }}>Go to Downloads Page</a>
<br>
</td>
I've tried making the value attribute equal to the file name getting passed in ex. value ="{{row.name}}" for the file type <input> above, but that doesn't keep the file chosen name on the page after submission either. I can't find any videos or posts that deal with this problem, so I would really appreciate any guidance. TIA!
I think setting a default value for an input field of type file is forbidden for security reasons.
However, if you want to keep the name of the selected file, you can aim for a transfer with AJAX. Here you can suppress the standard behavior of the form. The page is not reloaded and the form is not reset.
The example below shows you how it works.
Flask (app.py)
from flask import Flask
from flask import (
render_template,
request,
)
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/upload-file', methods=['POST'])
def upload_file():
if 'csvfile' in request.files:
file = request.files['csvfile']
if file.filename != '':
# handle file here!
return '', 200
return '', 400
HTML (templates/index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form name="my-form" method="post">
<input type="file" name="csvfile" />
<input type="submit" />
</form>
<script type="text/javascript">
((uri) => {
const elem = document.querySelector('form[name="my-form"]');
elem.addEventListener('submit', evt => {
evt.preventDefault();
const formData = new FormData(evt.target);
fetch(uri, {
method: 'post',
body: formData
}).then(resp => {
if (resp.status === 200) {
console.log('Submit successful.');
}
});
})
})({{ url_for('.upload_file') | tojson }});
</script>
</body>
</html>
I don't know if it is possible to default the value the file-input field shows but what you could do is just have a row above the input field showing the currently uploaded/chosen file (if there is any). So something like this:
<td>
<form class="" action="{{url_for('main.upload_file')}}" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="{{row.id}}">
{% if row.name %}
<p>Currently chosen file: {{row.name}}</p>
<p>You can select a new file below</p>
{% endif %}
<input style="margin-bottom: 5px;" type="file" accept=".csv" name="csvfile" id="upload"> <br>
<input style="margin-bottom: 10px;" type="submit" name="" value="Submit"> <br>
</form>
<a href={{ url_for('main.files') }}>Go to Downloads Page</a>
<br>
</td>

Upload and process a file in a MaterializeCSS form with Selenium

Html of the form:
<form action="" method="post" enctype="multipart/form-data"><input type="hidden" name="csrfmiddlewaretoken" value="nTfw60C2FSwLfGTvOlO6FITRnz4yq2HObLpcDw1enoqaT9JsD4ztaDJpCpBVBpS7">
<div class="file-field input-field">
<div class="btn">
<input type="file" name="uploaded" id="id_uploaded">
<span>Choose file</span>
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" id="id_path">
</div>
</div>
<div class="col s12">
<button class="btn-flat" id="id_submit" type="submit">Submit</button>
</div>
</form>
The problem is that a click on the file text input opens a file dialog and MaterializeCSS doesn't accept pasting a file path string. Also, only the filename without the full path is shown in the text input after a user selects a file in the dialog.
When the following code runs then the form invalidates with my no file provided error:
text_input = webdriver.find_element_by_id("id_path")
text_input.clear()
text_input.send_keys(path_to_file)
webdriver.find_element_by_id("id_submit").click()
Any suggestions on how to solve this problem and provide a file in tests? Any workaround could be an acceptable answer as I just want to test the functionality that takes place after submitting a file.

How to get value on drop box in Flask Python

I have a file XML. It's follow . I use Flask Framework Python to get query in search bar and value of current dropbox (e.g english or vietnamese). I use "POST" method get value when I enter or click "Search" button. But value of dropbox is null.
<form class="input-group">
<div class="input-group-btn search-panel" id="menu1">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span>Language</span>
</button>
<ul name ="btnLanguage" class="dropdown-menu" role="menu">
<li><a>English</a></li>
<li><a>Vietnamese</a></li>
</ul>
</div>
<input type="text" class="form-control" name="query" id ="query" placeholder="Search sentence...">
<span class="input-group-btn">
<button id ="btnSearch" class="btn btn-success" type="submit">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</button>
</span>
</form>
How can you help me. Thank you
#app.route("/search" , methods=["POST"])
def search():
print("True")
# read the posted values from the UI
_query = request.form['query']
print(_query)
_language = request.value['btnLanguage']
print(_language)
and Json Method:
$(function(){
$('#btnSearch').click(function(){
$.ajax({
url: '/search',
data: $('form').serialize(),
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
});
It is because ul-li is not a regular form control (Checkout this link for available form control in html). So jquery will not consider it when serializing form data. Solution : You need to write a script to append custom data with your form data or you should use <select> instead of ul-li dropdown.
Other problems with your code.
You are using click() event handler with a button having type submit so two events will occur, one is ajax you are calling and another is form will be submitted to server side with GET. To remove is issue you should be listening for form submit() event with preventing event propagation (check this answer).

Reload a csv file and call the same view with it

I have two templates (initial.html and index.html) containing (among others thing) a form. I use data from this form to generate a csv (data.csv) and then read it in the index.html thanks to d3 and parcoords.js. Each new submission generate a new data.csv
The thing is, on the first call, everything seems to work but the moment I try to submit the form with new values the visualization does not change (even if the file data.csv appears to change when I open it with TextEdit)
Moreover, the data (values in main.py ) I provide to the view does not change either.
I know it is not recommended to call the same view after a POST submission but even if I try to call a different view, both of the problems described below remains.
Relevant parts of code are as follows:
main.py
#app.route('/', methods=['POST','GET'])
def main():
global maxDepth
global numberOfRelated
if request.method=='POST':
url = request.form['url']
maxDepth = int(request.form['depth'])
numberOfRelated = int(request.form['numberOfRelated'])
values = crawling(url,maxDepth,numberOfRelated)
return render_template('index.html',var=values)
return render_template('initial.html')
the crawling function
def crawling(url,maxDepth,numberOfRelated):
start = time.time()
initialID = get_id(url)
videosId.append([0,initialID])
getAllID(1,initialID)
getVideoData(videosId)
if os.path.exists('static/csv/data.csv'):
os.remove('static/csv/data.csv')
with open('static/csv/data.csv','wb') as csvData:
dataWriter = csv.writer(csvData, delimiter='|', quotechar='|', quoting=csv.QUOTE_MINIMAL)
dataWriter.writerow(['Depth']+['ID']+['Title']+['Popularity']+['Occurency'])
for x in xrange(0,len(videosData)):
dataWriter.writerow([videosData[x].level]+[videosData[x].id]+[videosData[x].title.encode("utf-8")]+[videosData[x].popularite]+[videosData[x].occurence])
timeExecution = round(time.time() - start,1)
mostFrequent = mostFrequentVideo()
mostPopular = mostPopularVideo()
initialVideo = videosData[0]
return [initialVideo,mostPopular, mostFrequent, len(videosData), timeExecution]
The form
<nav class="navbar formSpace">
<div class="container">
<form class="form-inline" action="" method="POST">
<div class="service form-group">
<i class="fa fa-youtube fa-2x"></i>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mainForm" placeholder="https://www.youtube.com/watch?v=2HIuN5lxMCI" name="url" />
</div>
<div class="form-group minorForm">
<input name='numberOfRelated' type="text" class="form-control" placeholder="Number of suggestion" />
</div>
<div class="form-group minorForm">
<input name='depth' type="text" class="form-control" placeholder="depth" />
</div>
<div class="form-group navbar-right">
<button class="btn btn-success minorForm generate" type="submit"> Generate</button>
</div>
</form>
</div>
</nav>
main.js
var pc0;
var blue_to_brown = d3.scale.linear()
.domain([0, 5])
.range(["red", "#3498db"])
.interpolate(d3.interpolateLab);
d3.csv('static/csv/data.csv?_='+ Math.random(), function(data) {
pc0 = d3.parcoords()("#example0")
.data(data)
.showControlPoints(false)
.hideAxis(["Title"])
.hideAxis(["ID"])
.composite("darker")
.width(860)
.color(function(d) { return blue_to_brown(d['Depth']);})
.render()
.alpha(0.35)
.brushMode("1D-axes")
.reorderable()
.interactive();
});
Flask serves static files that tell the browser to cache the file rather aggressively. The default is to tell the browser to cache the file for 12 hours.
You can bypass this cache by adding a random value to the URL;
d3.csv('static/csv/data.csv?_=' + Math.random(), function(data) {
Now the browser will see this as a new URL each time and not re-use the cached file.
Well, I finally found the solution
The trick advised by Martijn Pieters works perfectly fine, the problem was coming from the format of my CSV. (I was using '|' instead of ',' and D3 didn't like that)

Categories