I'm trying to get a html page to run a js script from the static files of the host using Flask (as it's a test project it's a localhost) and for some reason every script comes back as a 404 - I'm using this file structure
¬static
¬html
¬user.html
¬js
¬script.js
https://i.stack.imgur.com/vIXzr.png
I've followed as many guides and other queries on fixing this but I don't get what else I'm missing. I've used <script src="js/script.js"></script> to call it, I've used src="{{url_for('static', filename='js/script.js') }}" in place of src="js/script.js, I've tried using just script.js instead of js/script.js, I've tried putting it in different places in the file tree and using as many ways as I can think of to call it from these places, I've downloaded plugins, I looked at official sites explaining how to create html and js and etcetera... Can't get anything to work
EDIT - solved, for some reason clearing my cache for the 2000th time fixed it. Copied the project to another device, same problem, fixed it by replacing js/script.js with static/js/script.js. That doesn't seem like that's how it should be but it works I guess
Static content in Flask loaded as follows:
<script src="{{ url_for('static', filename='js/script.js') }}"></script>
But in this case your html-template should be located in separate folder:
static
--js
scripts.js
templates
user.html
Folder templates is the default place where all html-templates are located in Flask.
Related
I have a situation where a minified js script tries to include another js file with a hard coded relative path.
More precisely :
I'm rendering an html page with url pattern path('room/<int:room_id>/', room, name='room'),
This page includes the first js lib with <script src="{% static 'js/firstlib.min.js' %}"></script>
I have js/firstlib.min.js in my static files dir, thus Django serve
http://localhost:8000/static/js/firstlib.min.js correctly.
The problem is that firstlib.min.js tries to include tanks/lib/otherlib.js using hardcoded relative path, using
http://localhost:8000/room/139/tanks/lib/otherlib.js
A dirty hack would be to replace tank/* with /static/tank/* everywhere in firstlib.min.js. But I'wondering if there is a better way to solve this issue, for example by dynamically rewriting url :
/room/<int:room_id>/<path>/somescript.js becoming /static/<path>/somescript.js (actually, the first script tries to include several other scripts the same way :-s)
This question already has answers here:
flask does not see change in .js file
(5 answers)
Closed 3 years ago.
I have a problem with Javascript in my app. I'm using Flask and I'm working in PyCharm. My html's are in the template folder and my Javascript is in static folder, so this is external file. It's called main.js.
These are the links to javascript in the html:
<script type="text/javascript" src="/static/main.js"></script>
<script type="text/javascript" src="{{ url_for('static', filename='main.py') }}"></script>
I tried both versions and I experienced the same issue with both of them. Both links would actually work for the first load of my page on localhost but every next change in my Javascript main.js file simply just wouldn't get recognized. For instance, I put alert() in main.js just to be sure that the links work, and they worked just fine. But then I deleted alert(), put there some other Javascript code and saved it, but still, this alert() would be active even though I deleted it from the main.js file. And this new code that I put in main.js, it appeared as if it wasn't there at all. So my question is why my main.js file doesn't work?
Am I missing something here? Has anyone experienced this kind of problem in Flask or any other Python (micro)framework?
Your second reference is for a py file, not a js file:
<script type="text/javascript" src="{{ url_for('static', filename='main.py') }}"></script>
When using Flask, the above is a better alternative to full paths, so change it to:
<script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script>
If your browser still doesn't refresh the javascript you should try to Hard Refresh the pages. On Chrome, this is done by pressing CTRLShiftR on a PC or CMDShiftR on a Mac. This should clean your cache and force reload js files.
Finally, if none of these work, you should check on your python code if the headers are being modified for a longer cache. You can 'force' a Flask request to have a shorter cache time by trying to include:
#app.after_request
def add_header(response):
response.cache_control.max_age = 300
return response
You can also try changing Flask app settings for no-cache:
app = Flask(__name__)
...
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
I would also try a different browser and check the network inspect tool (Chrome) to see if the files are being loaded.
I am getting problem in referencing Javascript file.
My all js files reside in my js folder:MyProject/Js/*.js
Now on my master page i am refering my file like this:
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-1.9.0.min.js" type="text/javascript"></script>
Error showing in console:
SyntaxError: expected expression, got '<'.
On searching i have found that this issue comes due to inappropriate referencing of js files so i have resolve this error by doing this:
<script src="../js/jquery-1.9.1.js"></script>
<script src="../js/jquery-1.9.0.min.js" type="text/javascript"></script>
This above solution works when my .aspx page would be like this:
MyProject/Admin/Abc.aspx //This will work
But problem will occur when any of my .aspx page would be like such:
MyProject/Admin/Subfolder/Abc.aspx // This will not work
My Abc.aspx page contains master page but now in this case this will not load my js files due to ../
So can anybody tell me whats the correct way to reference js files which will work in both the cases??
Note:I am referencing all js files in to my master page and my master page is in:
MyProject/MasterPage.Master
I think you can give a try:
1) Use Bundling to reduce the loading time (Your script will be shorter as well)
2) Use ~/ instead of ../ to make your script/code work even if you relocate the pages.
You can easily find the scripts and codes of jquery bundle if you create a new ASP.NET application in Visual Studio.
It all works in my local server, but when others try to deploy what I have done to the server, it fails.
the file system is the server something like:
SERVER_FOLDER
--homepage
----static
----templates
------404.html
----app.py
----config.py
for example: The server is: MY_SERVER
and then in my app.py, I use
#app.route('/homepage/')
#app.route('/homepage/index')
def index():
# TODO
to define the homepage, and #app.errorhandler(404) to redirect all the not found page to 404.html
So I can get access to my homepage with http://MY_SERVER/homepage/, a little different than my local server. That's one thing that I am confused.
What I think is that the app.py runs under the MY_SERVER rather than MY_SERVER/homepage right?
But, in this way, when I run a template in my template file, and the html template file will use the js file under the static folder. the response always shows the js file is not found.
when I use <script src="{{ url_for('static', filename='file.js') }}"></script>, it shows not found in MY_SERVER/static and return to 404
when I try <script src="../homepage/static/file.js"></script>, same result.
How to handle this?
Build toward your solution:
Get flask serving image files from static
Put an image in the static directory and call it from your browser: http://yoursite/static/some_image_there.jpg
Plug away until that works.
Get flask serving the js file directly to your browser
Now put your js file into static and do as you did for the image.
Plug away until you can call it from the browser:
http://yoursite/static/yourfile.js
get your html to call the js file from static
Now you know that there is no problem actually serving the file, and you know the exact url to it. So it's not a big step to getting the HTML to reference it and your browser to load it.
I have a problem with Javascript that keeps bugging me for quite a while now. I have an external file called search.js which is in the same folder as the .html file it's loaded into.
The piece of code I use in th HTML to load the javascript file is:
<script type="text/javascript" src="search.js"></script>
From all the websites I've read I can't find an issue here with the code.
Also, I know that the syntax in the javascript file has to be correct in order for it to work, so here is my Javascript code from search.js:
$(document).ready(function(){
$('#searchForm').submit(function(){
var lookfor = $("#billSearched").val();
alert(lookfor);
var a = $(this).attr('action');
alert(a);
a = a.replace("__search_term__",lookfor);
alert(a);
window.location.href = a;
return false;
});
});
I've runned this code in another project and it has worked just fine, all that I've changed was the names of the fields, i.e. billSearched.
If there are any other reasons for why Javascript doesn't load in my page please leave a message or a comment.
Thanks in advance!
EDIT
Full html code:
<html>
<head>
<title>Bills</title>
<script type="text/javascript" src="/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="/search.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body bgcolor="#0066CC" color="FFFFFF">
<table>
<tr>
<td style="color:white"><b>Products</b></td>
<td style="color:white">Price</td>
<form method="POST" id="searchForm" action="{% url ps.views.search searchTerm='__search_term__' %}">
{% csrf_token %}
<td><input type="text" id="billSearched"></td>
<td><input type="submit" value="Search"></td>
</form>
</tr>
{% for x in products %}
<tr>
<td style="color:white">{{ x.name }}</td>
<td style="color:white">{{ x.price }}</td>
</tr>
{% endfor %}
</tr>
</table>
</body>
From the tags and your template code, I gather that you are using Django. To understand your issue, you'll have to understand how Django views work relative to your browser, and what happens when your browser issues a request for a given url.
What happens on the Django side:
What happens when you request an url is that your base urls.py file will be searched for pattern matching your url. If a pattern is encountered, then the corresponding view will be called.
The viewwill carry out its logic, and will use a template to render its response into html.
What happens from your browser's point of view
The browser requested an url, and received a response, it is not aware of the fact that a view was called, and that it fetched a template somewhere.
What this means to you
The fact that your search.js file is located next to your template is totally irrelevant, as your browser never requested any file from this directory, it's the view that did, when it fetched its template.
Actually, your browser's request for search.js will be forwarded to Django by your webserver and will (most likely) result in a 404 error, unless search.js resolves to a view in your urls.py.
How you can use this to solve your issue
You'll need to serve your search.js file from a directory that can be accessed by the browser. Usually, this is done in three steps:
Configure your webserver so that it serves any path starting with /static/ on its own (somehow, this means not forwarding the request to Django).
In Apache, you'd use the following rule: Alias /static/ /YOUR/STATIC/DIRECTORY/
Configure Django's settings.py to use /YOUR/STATIC/DIR as STATIC_ROOT, and /static/ as STATIC_URL.
Put your search.js file in your /YOUR/STATIC/DIR/
Use src="/static/search.js to reference your file in your html template.
One last thing: if you're using the development server, you might need to ensure your STATIC_URL starts with the full path to your server, including the port. (Or you might have issues with browser security policies).
A few additions:
Your should be using template tags so that you don't have to write /static/ in your template.
You should be using manage.py collectstatic to autimatically put static files in your static directory.
Most importantly, you should investigate what Django's MVC (or MTV) model is about.
Paths prefixed with / points to the root - not the current folder. In this case you want to drop the / prefix.
Your HTML files at project/ps/templates/bill.html which links a JS script /search.js means it's looking for the files in the completely wrong location.
For instance, you can see how it resolves the path if you add a link to /search.js in your HTML.
For illustrative purposes, create an HTML file on your desktop:
<html>
<body>
Hello
World
</body>
</html>
When you hover over the link you will see that Hello it resolves to file:///foobar.txt and World resolves to the path to your desktop - in my case file:///C:/Users/thm.ARC/Desktop/foobar.txt.
I had to make a mix of your answers in order to fix the problem but eventually it was fixed. I had to make the following modifications:
Add the '/static/' folder to STATIC_URL and STATICFILES_DIRS in the settings.py file
Import the .js files (search.js and the jQuery source) with the following commands, in this order:
<script type="text/javascript" src="/static/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="/static/search.js"></script>
And make the according file structure, placing the "static" file in the project's root directory.
i.e.
Psroot:
psApp
static
templates
and the rest of the files (settings.py, urls.py, manage.py, etc.)