Static does not loads static files in Django - django

This is my directory structure
app_web
_init_.py
settings.py
urls.py
wsgi.py
upload_app
migrations/
static/
js/
alert.js
templates/
upload.html
_init_.py
admin.py
apps.py
models.py
tests.py
views.py
db.sqlite3
manage.py
In settings.py , my
STATIC_URL = '/static/'
and in my upload.html
{% load staticfiles %}
<script type="text/javascript" src="{% static "js/alert.js" %}"></script>
It does not works and throws 404 error everytime. I even tried load static but it still cannot load anything from static folder and throws 404 error.
I am using Windows 10 machine and Django==1.9

The idea was to create a static directory outside the upload_app folder. The reason is that in the settings.py the BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) . That means one directory above is the base directory, so it will start searching static/ from that directory. But it will never find it as I placed inside upload_app/static .
Also, I need to work on putting templates outside the app upload_app as it's not generally best practice to keep templates inside the app.
looking for other suggestions in structure

Related

Having issue in loading files from static folder

I am new to django and I am having issues while following a tutorial on YouTube. Please help me so my static page which I changed into dynamic will load with changes that I made. Everything is working fine except when I try to run it by using {% static %}. I also told the system about static stuff through {% load static %} but it not showing pictures which I try to show through the static folder.
Summary
Pictures are not showing on the web page.
Files are not available from the static folder.
Not sure exactly what your problem is here but, as I understand it, you are trying to use images from your static folder in a django template. This can be achieved by correctly configuring django and using template tags.
In Development
To make this work with the development server, you need to create a folder called static inside each app's folder. For example, your project's file structure could look like this:
project
|_ project
|_ app
|_ static
|_ app
|_ image.png
|_ templates
|_ app
|_ home.html
|_ __init__.py
|_ admin.py
|_ models.py
|_ tests.py
|_ urls.py
|_ views.py
|_ db.sqlite3
|_ manage.py
Then, you simply access your image from the template home.html by adding {% load static %} at the beginning of the file and using {% static "app/image.png" %} wherever you want to use your image. Note that this template tag basically gives you the url to the static file you want to show. So, actually, you should insert the image like this:
<img src="{% static 'app/image.png' %}" />
In Production
In production, we need to collect all the static files from the different apps in one common place, so that the server can easily find them. We do this with the useful django app staticfiles, which we can configure in the settings.py file.
settings.py
Make sure your settings.py includes the following lines
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
INSTALLED_APPS = [
...
'django.contrib.staticfiles',
...
]
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
You can replace 'static/' with whatever you want to be your static url. You can replace 'staticfiles' in STATIC_ROOT with the name of the root folder where you will collect your static files. This folder must be (with this configuration) in your project's base directory - the same folder where you have your database (db.sqlite3). For example:
project
|_ project
|_ app
|_ staticfiles
|_ db.sqlite3
|_ manage.py
When you run python3 manage.py collectstatic, all the static files of each app of your project will be copied into the STATIC_ROOT directory, so they are all available from the same place. Your file structure will look like:
project
|_ project
|_ app
|_ staticfiles
|_ app
|_ image.png
|_ db.sqlite3
|_ manage.py
Finally, you will have to tell your production server where the staticfiles directory is, and you are all set to go (how to do this depends on the hosting service you are using).
Hope this helps!

Django template namespace

I read that for every app of my INSTALLED_APPS in settings.py, Django will look for HTML templates inside the templates subdirectory. But I'm a little confused.
For instance, when creating my HTML templates in the initial project below:
myproject/
manage.py
myapp/
__init__.py
settings.py
urls.py
wsgi.py
templates/
Should I simply create a template subdirectory within the myapp directory and put all my HTML templates inside?
Almost correct, the templates subdirectory within myapp also needs myapp subdirectory which will contain all of your app html files. Also do not mix core project files such as settings.py and wsgi.py within app, better separate them out, hence the better structure would be:
myproject/
manage.py
mysite/
__init__.py
settings.py
wsgi.py
myapp/
__init__.py
urls.py
views.py
templates/myapp/

Django folder structure

What would be a good structure (best practise) for the folders in a Django application (1.7)?
I'm not sure where to put the static data and file Uploads.
In all my projects it turns out different, but currently I have something like this (I left out a few obvious folders/files):
project/
bin/
include/
...
src/
manage.py
main/
- settings.py
- urls.py
signup/
static/
static_/
+ css
+ img
+ js
static/
templates/
- index.html
- base.html
- ...
uploads/
And also, I'd prefer to see url's like for example site.com/css/file.css instead of site.com/static/css/file.css , but somehow thats more complicated then it seems. How can that be accomplished?
I use the the following in setting.py (using Django v1.6.8 at the moment)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
#TEMPLATE_DIRS = (os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "static", "templates"),)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),)
This gives me a folder layout
project/
manage.py
project_app/
- settings.py
- urls.py
someother_app/
- admin.py
- models.py
- views.py
static/
css/
javascript/
templates
admin/
someother_app/
- base.html
- index.html
media/
I'm not sure what you mean when you say site.com/css/file.css. Something like <link rel="stylesheet" href="{{ STATIC_URL }}css/jquery.asmselect.css"> in the <head> of base.html uses the Django Framework to present your .css files. Why not use what is there? Saves time and effort.
Tommy.
Here is a recommendation for the Django project layout from the book Two Scoops of Django:
repo_root/
.gitignore
Makefile
docs/
README.rst
requirements.txt
django_project_root/
manage.py
media/
django_app_root/
static/
templates/
config/
__init__.py
settings/
urls.py
wsgi.py
and is considered a three level project layout where:
Top Level (repo_root): high-level files required for deployment
Second Level (django_project_root): actual django project
Third Level (config): the django project configuration files.
Regarding file Uploads I would upload them from the browser directly to Amazons S3 file storage (or similar service). Otherwise you're hogging bandwidth and CPU time. Or if you must then in the media folder ^ and for security reasons please validate the file types uploaded.

Statics Files Django on Heroku Deployment

I have my app runnning in Heroku, everything works really good with my models and forms, but there is a problem, I can't see any of my styles neither for my templates not for Django Grappelli, how can I solve this problem?
Thank you.
Check the path that your images/styles are trying to reference. Ensure that your STATIC_URL is a relative path. Also ensure that your STATIC_ROOT and STATIC_URL are not the same.
Ex:
settings/base.py
from unipath import Path
# Project directory root assuming: yourapp.settings.base
PROJECT_DIR = Path(__file__).ancestor(3)
# Static files
STATIC_ROOT = PROJECT_DIR.child("static")
# URL prefix for static files.
STATIC_URL = '/static/'
This layout follows the directory structure similar to:
project_name/
|-- app 1
|-- models.py
|-- views.py
...
|-- project_name
|-- settings
|-- base.py
|-- local.py
|-- dev.py
...
Also by default Heroku should collectstatic when you upload your project however if you have modified this setting ensure to call:
python manage.py collectstatic
you can then check to see if static files are present in the specified folder (in the example above it would be in /static/

django not displaying image

I started with a django app and tried displaying an image in the home page. But the image is not getting displayed.
My settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR,"media")
MEDIA_URL = "/media/"
My urls.py:
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'myapp.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'',include('users.urls')),
)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My home.html:
<html>
<head>
<title>MY SITE</title>
</head>
<body>
<img src="/media/image/myimage.jpg" alt="my image"/>
Welcome to my site
</body>
</html>
I get the text my image displayed instead of the image
ok, so I set up a simple 'paired-down' working example of this so no moving pieces were missing. Some Notes:
I used django 1.6
If you want to use a 'scale-able' delivery of static images you will want to follow
the django-1.6 staticfiles documentation which is what this example provides.
This means that you need to hack-n-slash your MEDIA references. ( MEDIA is really meant for file upload's) and you dont need to fool with the staticfiles_urlpatterns in your urls.py file. As you get this behavior out-of-the box when you add 'django.contrib.staticfiles' to your settings.py
Overview: Here is what your file tree-layout will look like in django 1.6, and the file structure that I am referencing in this answer.
├── djproj
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py
├── manage.py
└─── myapp
   ├── admin.py
   ├── __init__.py
   ├── models.py
   ├── static
   │   └── myapp
   │   └── myimage.jpg
   ├── templates
   │   └── index.html
   ├── tests.py
   └── views.py
Step 1: Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
Step 2: In your settings file, define STATIC_URL, for example:
STATIC_URL = '/static/'
Step 3: change your home.html to look like this ( I used index.html in my example )
[ PROJECT_HOME/myapp/templates/index.html ]
<html>
<head>
<title>MY SITE</title>
</head>
<body>
{% load staticfiles %}
<img src="{% static "myapp/myimage.jpg" %}" alt="My image"/>
Welcome to my site
</body>
</html>
Make sure to read the django-1.6 staticfiles documentation related to STATICFILES_STORAGE so you understand what these template tags are buying you. Hint: python manage.py collectstatic
Step 4: ( you may have already done this, but I did not see it) Make sure that TEMPLETE_DIRS is defined in your settings.py and includes your home.html ( key here is that django's template engine needs to be serving this as we will be using some template tags)
[ PROJECT_HOME/djproj/settings.py ]
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
BASE_DIR + '../myapp/templates',
)
Step 5: build a view that renders your home.html page.
[ PROJECT_HOME/myapp/views.py ]
from django.shortcuts import render_to_response
def index( request ):
return render_to_response('index.html')
Since this is a bit convoluted, and there are several moving pieces here: here is a changeset that shows the complete 'changes'
You can of-coarse pull the entire github project if any of this is confusing.
django-staticfiles-setupexample
Final Note: STATIC files were not always handled this way in django. The MEDIA dir used to be the settings attr you were after. So this answer is for Django 1.6 ( staticfiles were added in django version 1.3)( the directory layout was changed in django 1.5).
You can ( as you were trying to do) hardwire your media dirs to the STATIC defines. Altho I do-not recommend this. Which is why I did not describe how to do it this way.
You are adding the media urls too late in the list. Django will try to match each urlpattern in succession, stopping when it gets to the first one. In this case, it matches on r'' and doesn't get to the static files or the media urls.
You may be able to put each pattern in the single call to patterns(), instead of using +=. That would be the cleanest, but I can't test it here. A sure-fire way to do it would be to pull the "users.urls" line out and add it later, like so:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += url(r'',include('users.urls'))
I'd recommend you set DEBUG = TEMPLATE_DEBUG = True and request the image URL directly.
You'll get Django debug output either showing that the URL can't be matched or the file path it's actually looking for.
The settings look generally correct although you've not shared BASE_DIR which is important in this case.
I had been struggling with the issue for like an entire day yesterday... I finally gave up and moved on creating my site without worrying about the images. Then today I decided to check the responsiveness of the site. I found out that my URLs were okay since I had strictly been following the documentation and best practices. The chrome console was saying:
Failed to load resource: net::ERR_BLOCKED_BY_CLIENT
The issue was with HTTP Referral Policy. Check them out. So after doing some research, this helped a lot, I found out that AdBlock was blocking my referred images. Apparently, my /media/ path was flagged in one of their regex patterns, deciding that my images were redirections to Ads. The ironic thing is that my website is about ads... so it must have heavily factored in, as my site has words like 'ad' in its url patterns. Long story short, I disabled AdBlock and my images now render. So I think it might be worth considering that even with best practices in your Django code, such an error could be caused by something with your browser!