Having issue in loading files from static folder - django

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!

Related

Serving static files in Flask production

I have the static folder in my app folder and that's where I have js, css, images etc. folders.
I reference them like this in my templates:
<script src="/static/js/main.js"></script>
and it works locally. But, when the app is published to production, I get a 404 for all static files. I'm new to flask so I guess I'm serving them wrong.
I don't have the static folder set as a designated static files folder anywhere in the app - is it done automatically if it's called 'static' or do I need to set it in code?
My project structure:
app/
├── static/
│ └── js/
| |__ css/
├── templates/
│ └── index.html
└── __init__.py
application.py
application.py:
from app import create_app
application = create_app()
init.py:
from flask import Flask
from config import BaseConfig
def create_app():
server = Flask(__name__)
server.config.from_object(BaseConfig) # this is just for the secret key
return server
Flask automatically adds a static view that takes a path relative to the $YOUR_APP/static directory and serves it.
Typically you would include your js/css files in your templates like so:
{{ url_for('static', filename='main.js') }}
First part of the solution was Bert's answer above which described how to correctly reference assets from the templates.
The other part I was missing was this:
server = Flask(__name__, static_url_path="", static_folder="static")
instead of what I had before:
server = Flask(__name__)
Adding static_url_path and static_folder fixed the issue for me.

How to use startproject --template? (Django 2.2)

I'm attempting to create a Django templates directory via django-admin startproject and --template.
I've tried: django-admin startproject main_project --template=./templates
However it only creates an empty main_project directory there is nothing reflecting a Django instance in this directory (ie. no urls.py, settings.py, wsgi.py, etc.)
- desktop/
|_ main_project/ # directory where startproject will be executed via CLI
|_ templates/
I'm expecting a project Python package to be created as described here:
https://docs.djangoproject.com/en/2.2/intro/tutorial01/#creating-a-project
mysite/
manage.py
mysite/ # or main_project for my example
__init__.py
settings.py
urls.py
wsgi.py
I'm only getting:
- desktop/
|_ main_project/ # directory where startproject will be executed via CLI
|_ main_project
|_ #empty directory
|_ templates/
|_ venv
As per the docs https://docs.djangoproject.com/en/2.2/ref/django-admin/#cmdoption-startapp-template
Perhaps try the command with the —template flag before the project name

Static does not loads static files in 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

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/