I dont know if I did this right but during development phase I placed all my static files on my project's main directory, it looks like this:
myproject
myapp
manage.py
myproject
- settings.py
- urls.py
...
static
- css
- somecssfile.css
- js
- somejsfile.js
...
templates
now my settings.py file looks like this:
STATICFILES_DIRS = [BASE_DIR / "static"]
STATIC_URL = '/static/'
after I deployed my project into pythonanywhere I added STATIC_ROOT:
STATIC_ROOT = '/home/jeremiramos/cvs/staticfiles/'
it does copy my static files to staticfiles folder when I do collectstatic on pythonanywhere console but it cannot read/load the static files I used on each and every page including admin page.
and my staticfiles settings on pythonanywhere looks like this:
I checked my console and I got some errors:
Refused to apply style from 'http://jeremiramos.pythonanywhere.com/static/css/index.css/' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
I've tried checking the forums of pythonanywhere.com but it doesn't seem to help.
Can anyone please explain what did I do wrong and what should I do? Thank you!
Since http://jeremiramos.pythonanywhere.com/static/css/index.css loads the actual file, it means that static file mappings are OK. Trying the url with trailing slash (as in the error message you've shown) gives 404 and MIME type error message might be a symptom of it. Remove trailing slash from the url and check if that solves the issue.
Related
New-ish coder and first time stack overflow poster. I've made a django project with 3 pages. Sometimes no pages are found, sometimes the index page loads without 404 error but I can't link to other pages and the css files I've pointed it to doesn't render.
Errors I'm getting is:
404 error
I have slept on the problem, looked up file formats to make sure my project and app url.py is correct. added app to settings. imported correct classes. I have also tried clearing my browser data on chrome and using a different browser.
If anyone could take a look at my small project on github that would be amazing. https://github.com/Connell-L/portfolio_website is the link or if anyone wants me to post code files on codepen or something I'm more than happy to do it.
Edit: https://github.com/Connell-L/portfolio_website/tree/branch1 it's here sorry lol
You need to add STATICFILES_DIRS and STATIC_ROOT to your project settings.py
like this:
BASE_DIR = Path(__file__).resolve().parent.
the above line of code has to be at the bigining of your settings.py file
STATIC_URL = "static/"
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
I'm testing one and the same application both on the default Django server and on Apache and I see a lot of big differences. I managed to resolve some of them, but at this moment I'm unable to resolve a major difference. So, in project settings.py file I have this code:
MODULES_DIR = BASE_DIR + '/system/modules/'
for item in os.listdir(MODULES_DIR):
stat = os.path.join(MODULES_DIR, item + '/static')
if os.path.isdir(os.path.join(MODULES_DIR, item)):
INSTALLED_APPS += ('system.modules.%s' % item, )
STATICFILES_DIR += (stat, )
APPS_DIR = true
This code is supposed to populate INSTALLED_APPS dynamically, based on the contents of BASE_DIR + '/system/modules/' folder. In other words, if there is a folder inside /modules, this folder becomes an application. Likewise, I build dynamically STATICFILES_DIR - in this case it is supposed, that every single folder/application (which is inside /modules folder) has a /static folder with static contents - js, css etc. For example, it may be such a construct:
\modules
\DefaultModule
__init__.py
urls.py
views.py
\static
test.js
\templates
DefaultModule.html
And DefaultModule.html in this example loads static files like this:
<html>
<head>
{% load static from staticfiles %}
<script type="text/javascript" src="{% static "test.js" %}"></script>
It is rather interesting, but on default Django server this logic works perfectly, so that when I go in my browser to localhost/DefaultModule/, I see a template DefaultModule.html loaded and I see test.js file loaded from http://localhost/DefaultModule/static/. However, on Apache the template is rendered too, but the test.js file is loaded from http://localhost/static/ what eventually results in a 404 NOT FOUND error. So, for some reason Apache server does not take into account STATICFILES_DIR. And yes I checked its (I mean STATICFILES_DIR) contents and it is the same. In both cases STATICFILES_DIR contains modules/DefaultModule/static/, but on Apache it is ignored for some reason. Hope someone can help. Thanks!
I think you should read the Django docs on static files. Looks like you're falling into the simple and old Django Static File Hosting an Apache
Check it out and let us know.
The problem looks similiar to the problem here:
Pythonanywhere, how to use static files? url? ,but I cannot comment there.
I've started learning Django and when everything worked on localhost that on PythonAnywhere it does not.
At projectname/settings.py I've set:
STATIC_ROOT = "/home/*username*/*projectname*/Static/"
STATIC_URL = "/s/"
and even URL's from static folders in apps.
After trying to run
python3 manage.py collectstatic
every file *.js, *.css and images were coppied to the projectname/Static folder.
But... none of them were recognized after launch of the app.
I've set
{% load static %}
used tags
{% static "assets/css/theme.css" %}
At the source code I can see the proper link to css file:
<script src="/s/assets/js/seen.min.js"></script>
And everything would be fine, but the "/s/" isn't recognized by django and it tries to find the view in urls.py.
After opening the link to: username.pythonanywhere.com/s/assets/js/seen.min.js I've got standard, debug 404 page with the path of urls.py tries.
How to solve this annoying problem?
You need to add a static file mapping on the web app. Look for the "Static files" heading on the web app tab.
From what I can tell of your setup, you'd need to put "/s/" for the URL and "/home/*username*/*projectname*/Static/" for the directory.
I have a single page app (SPA) that I am running off of Google App Engine (GAE). GAE does three things:
Serve the index.html file
Serve the static files (JS, CSS, etc.)
Serve the dynamic files (images, text, etc. via REST)
I use the following app.yaml configuration.
handlers:
- url: /app
static_dir: app
- url: /.*
script: main.app
My understanding is that this should match any requests going to the /app folder, which would serve my static files. All the REST services and the main index page would then be caught by the /.* and processed by main.py
However, I see the following behavior:
If I remove the /app handler, I can successfully serve the index.html (via Jinja templating) and the REST services (such as localhost/subjects/). However, I cannot see the static files (as expected).
If I add the /app handler, the index.html file does not serve and gives an "Internal Server Error" IOError(errno.EACCES, 'file not accessible', filename). However, when I request a static file such as: "localhost/app/app.js", this succeeds.
Is there something that I am missing here? I do not understand why the two would conflict.
Thank you!
Notes:
Google App Engine 1.8.9, Python 2.7, Developing locally
EDIT:
Here is the Python code I am using to serve the page
path = os.path.join(os.path.dirname(__file__), 'app')
jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(path))
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
template_values = {}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
My directory structure is as follows:
/
main.py
app.yaml & etc.
app
index.html
app.js
Module A
moduleA.tpl.html
moduleA.js
Edit 2:
I moved index.html to the root directory (/), and then used the following python code:
path = os.path.dirname(__file__)
jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(path))
It (very interestingly) appears that the "double mapping" of the index.html to the Jinja template and to the static directory files caused a problem. I wonder what is the best practice way to do this. I use Jinja for one reason: adding the (GAE generated) login/logout link to the index.html file. Other than that, there is no reason for using it.
Python is by default unable to access files or directories marked as static in App Engine. You can add application_readable: true to your handler mapping to enable this.
Another solution would be to move the index.html away from the static folder since it in fact isn't a static file but instead is a jinja template for Python.
Related question: Read a file on App Engine with Python?
Documentation for application_readable
application_readable
Optional. By default, files declared in static file handlers are uploaded as static data and are only served to end users, they cannot be read by an application. If this field is set to true, the files are also uploaded as code data so your application can read them. Both uploads are charged against your code and static data storage resource quotas.
Ok it might explains scenario #2, how do you access the index.html? If you add /app to the handler and your request url is something like /app/index.html it will serve from the static dir.
On your scenario seems your url does not contain /app, therefore it goes to the 2nd handler rule which is going to main.app.
However since you put the html inside the /app, appengine treats it as static file. If you want to serve the file from jinja template, you should not put it in static_dir
Jinja templates (or Django, Mako etc) has no requirement to be sat in a publicly accessible folder. They are always called via a handler in the application and compiled in the application before serving to the user.
It is common practice to put these in a /templates directory. There is no reference to this directory in app.yaml, it is purely used internally to serve the templates. Check out some of the boilerplate apps in github (search 'gae boilerplate'). This one is minimal and uses Jinja so may be a good example for you https://github.com/SoulAuctioneer/notvanillae
Like the 1 billionth static file question about Django 1.3. I've been searching and trying so many things but nothing seems to work for me. Any help would be appreciated. Will try and give as much information as possible.
URL FILE
urlpatterns = patterns('',
url(r'^projectm/statictest/$','project_management.views.statictest'),)
VIEW
def statictest(request):
return render_to_response('statictest.html',locals())
TEMPLATE
<html><head><title>Static Load Test Page</title></head>
<body>
{% load static %}
<img src="{{ STATIC_URL }}testimage.jpg" />
</body></html>
SETTINGS
STATIC_ROOT = '/home/baz/framework/mysite/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = ('',)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_DIRS = (
"/home/baz/framework/mysite/templates"
FILES
-bash-3.2$ pwd
/home/baz/framework/mysite/templates
statictest.html
-bash-3.2$ pwd
/home/baz/framework/mysite/project_management/static
-bash-3.2$ ls
testimage.jpg
Not too sure if there is any other information that would be helpful. But basically when I go to this test page and check the page source, the url is pointing to
<img src="/static/testimage.jpg" />
However the image does not load. I have tried this on multiple browsers too. Maybe I am missing an imort statement somewhere?
cheers for the help
Are you using the built in runserver command or do you serve the Django app some other way?
If you use runserver then your problem is that you don't tell Django where to find your static assets in the filesystem. You need to set STATIC_ROOT to a filesystem path where your static assets can be found. Try setting it to: /home/baz/framework/mysite/project_management/static/
If you are using a different server (like gunicorn behind Nginx for example) then it is the responsibility of the front-end server to intercept requests for /static/ and serve them for you.
Also remember to run the ‘collectstatic’ management command once you have set ‘STATIC_ROOT’.
https://docs.djangoproject.com/en/1.4/howto/static-files/#deploying-static-files-in-a-nutshell