Static file issue when deploying an Django app - python

I understand there are some existing problems/answers about loading static files in production.
However, my case is somehow different. My Django app not is deployed as the main app of my website (not in the public_html folder in the server), but an additional app (in a folder outside public_html). The server folder directory is like this
home/myaccount/
├── public_html
| └── static (not exist, location 1)
├── mydjango
└── static (generated by collectstatic, location 2)
└── css, fonts etc.
In my settings.py, STATIC_ROOT = os.path.join(BASE_DIR, 'static/') and STATIC_URL = '/static/'.
Currently, the browser will look for static files in the non-existing location 1, i.e., www.mypage.com/static/..., instead of location 2. 404 errors return.
My question is that how I can change STATIC_ROOT and STATIC_URL or other settings to make the browser look for location 2 instead of location 1?

If you are using Linux server then an easier solution is to create a symbolic link of location 2 static folder in location 1.
ln -s /home/myaccount/mydjango/static /home/myaccount/public_html/static
Another solution can be to create STATIC_ROOT path to point to public_html folder.

Related

Collect Static creating a clone of my static files folder Django

I need to refresh a js file in my static files folder, however whenever I run python manage.py collectstatic, a clone of my static files folder is created in a diffrent part of the project, and the js file is still not updated. I tried changing the STATIC_ROOT variable in the settings.py file to the actual location of my static folder, but it doesn't seem to refresh because the collectstatic warning message in the console says its going to be saved in a completely different location.
The Structure of my project is
resume_V6-test
-resume
-home
-static (actual location)
-resume
-settings.py
-store
-staticfiles (clone of the static folder)
-users
and my settings.py is
# Commented out the location it was before I tried fixing the error
#STATICFILES_DIRS = [
#os.path.join(BASE_DIR, "static"),
#'/resume_V6-test/resume/home/static',
#]
#STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_ROOT = os.path.join(BASE_DIR, 'home/static')
STATIC_URL = '/static/'
And the error message is
python manage.py collectstatic
You have requested to collect static files at the destination
location as specified in your settings:
C:\resume_V6-test\resume\staticfiles
This will overwrite existing files!
Are you sure you want to do this?
Thanks
STATIC_ROOT is the output destination for the static file. E.g. this is where collectstatic collects all the static files to (read here https://docs.djangoproject.com/en/3.0/howto/static-files/)
The default is to collect all static files from all apps from /static directory of each app.
If you want extra location to collect from, you can use the STATICFILES_DIRS settings. (https://docs.djangoproject.com/en/3.0/ref/settings/#std:setting-STATICFILES_DIRS)

STATIC_ROOT = '/static/' collects my static files outside my workspace directory

i have in my settings.py used
STATIC_ROOT = '/static/'
to collect the static files
this is my static_path settings
STATIC_PATH = os.path.join(BASE_DIR,'static')
when i run the collect static code django makes a static folder outside my workspace folder,should't it collect all the static files in the static folder which i have already created?
I think you've confused the STATIC_ROOT and STATIC_URL and STATICFILES_DIRS setttings.
To tell Django to serve your static files from example.com/static/, set
STATIC_URL = '/static/'
You shouldn't set STATIC_ROOT = '/static'. This is telling Django to collect your static files in /static/ on your disk, which is outside of your workspace.
STATIC_ROOT is the directory where the static files will be collected. It should be something like
STATIC_ROOT = '/var/www/example.com/staticfiles/'
If you don't want to hardcode the directory, you could do something like:
STATIC_ROOT = 'os.path.join(BASE_DIR, "staticfiles"),'
You would then configure your webserver (e.g. Nginx or Apache) to serve the files in the STATIC_ROOT.
Finally, STATICFILES_DIRS is a list of locations that Django will search for static files when you run collectstatic. The files will be copied from that directory to your STATIC_ROOT. Therefore you need to make sure that the STATIC_ROOT is not included in STATICFILES_DIRS.
Basically you can create multiple 'static' folders for different applications of Django project and those can be used in development. But whenever you go to production servers and to serve the all static files from the same place then you need this functionality in which you can collect all static files from different directory to one directory out of your workplace.
project_name
- project_name
- static
- static files goes here which are common
- __init__.py
- settings.py
- urls.py
- application_name
- static
- static files goes here which are related to application only
- __init__.py
- settings.py
- urls.py
- static - This is common place where all static files will be placed after collectstatic command for productions only.
According above structure you can understand you can server static files using different server like CDN.
Let me know if you are not satisfied with answer. Thanks.

More Django static 404 issues - paired with ember

I've seen lots of different posts regarding the Django static file issues. Unfortunately, none of them seem to help me. My django admin css is fine, however static files are giving my a 404 error. Here is a description of what my problem:
In settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = '/Users/me/develop/ember/myproj/static/'
In urls.py:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
My project directory:
> static
> myproj
> app
> templates
> ember.hbs
> img
> test.jpg
Inside my ember.hbs I reference the test.jpg, but I get a 404 error. It's weird because I can actually pull up the image using:
file:///Users/me/develop/ember/proj/static/myproj/img/test.jpg
I have no idea what to do to fix this, I've tried using the STATICFILES_DIRS method mentioned here: https://docs.djangoproject.com/en/1.8/howto/static-files/
but nothing seems to be working.
Thanks in advance!
More information: Django 1.8 and Ember-CLI.
I'm hosting the ember project within the static dir.
I'm running python manage.py runserver and running django on port 8000 at the same time as running ember s and running the application on port 4200. I'm using CORS-headers (https://github.com/ottoyiu/django-cors-headers/) to allow cross-site calls on development.
Static files will be discovered in "apps" that you create (found in INSTALLED_APPS) or in additional directories that you specify in STATICFILES_DIRS.
Let's say I did:
django-admin.py startproject myproject
And then:
cd myproject
./manage.py startapp myapp
mkdir myapp/static
mkdir myproject/static
Would give you a directory structure that looks something like
/Users/me/develop/myproject/
> myapp/
> migrations/
> static/
> __init__.py
> admin.py
> models.py
> tests.py
> views.py
> myproject/
> static/
> __init__.py
> settings.py
> urls.py
> wsgi.py
> manage.py
And then in settings.py you add "myapp" to INSTALLED_APPS.
In this structure, myapp/static/ files will be automatically discovered by Django because it is an installed app with a static directory. However, myproject/static/ files will NOT be discovered automatically because "myproject" is not in INSTALLED_APPS (and it shouldn't be).
This is because of the default STATICFILES_FINDERS setting, which is:
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.FileSystemFinder',
]
The first finder, AppDirectoriesFinder, scans the directories of all of your INSTALLED_APPS, and discovers any "static" folders they might contain.
The second finder, FileSystemFinder, scans extra directories that you specify in STATICFILES_DIRS, which is an empty list by default.
So if you want those files in /Users/me/develop/myproject/myproject/static/ to be discovered (as you probably do), you can add this to your settings.py:
from os import pardir
from os.path import abspath, dirname, join
# Get the root directory of our project
BASE_DIR = abspath(join(dirname(__file__), pardir))
# Add our project static folder for discovery
STATICFILES_DIRS = (
# /Users/me/develop/myproject/myproject/static/
join(BASE_DIR, 'myproject', 'static'),
)
Now, all of this is separate from STATIC_ROOT, which is a place where all static files are copied when you run ./manage.py collectstatic. For projects just starting out, this is usually in the project root folder: /Users/develop/me/myproject/static/
So we would add, in settings.py:
# /Users/me/develop/myproject/static/
STATIC_ROOT = join(BASE_DIR, 'static')
But this is only really used in production—it's a way to compile all of your static assets into a single spot, and then point /static/ at it with your server (e.g. NGINX).
During development, you can skip collectstatic altogether, and have Django discover and serve your static assets on the fly. Django provides a "serve" view to do this in django.contrib.staticfiles.views.serve.
Try this in your urls.py:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles.views import serve
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
urlpatterns += [
url(r'^static/(?P<path>.*)$', serve),
]
In your example, you are asking Django to serve files from STATIC_ROOT, which is also fine, but requires you to run ./manage.py collectstatic first, and every time your static assets change—which can be a hassle.
Ember and Django really shouldn't live in the same project. They are completely different frameworks with different tooling.
Think of your Django project as the backend application that serves an API. Think of your Ember project as one of possibly many clients that will consume your API. Others might include mobile applications, partner services, and so on.
When I start a new project that is going to use Django and Ember, I start a Django project called "myproject":
django-admin.py startproject myproject
And separately, an Ember project called "myproject-web":
ember new myproject-web
In development, I'll have two tabs open in Terminal.
First tab:
cd myproject
./manage.py runserver
Second tab:
cd myproject-web
ember serve
In production, I'll have two different servers, one at app.myproject.com that serves the Django application, and another one at myproject.com that serves the Ember application.
Later on, I might start a Swift project in a repository called "myproject-ios", and a Java project called "myproject-android". You get the idea.
In order to serve the static files into your django project you just need to add these lines to your `settings.py
STATIC_URL = '/static/'
STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
STATIC_PATH,
)
and then in the main stucture of your project dictory needs to be like
>Project_dir
>App_dir
>static_dir
>templates
>manage.py
place your css, js, and other static contents into your static_dir

What is the ideal directory structure for Django deployed app on openshift?

I am successfully deploy my application in open shift with first hello message but now
I want an ideal directory structure for deploy on openshift this Thanks
Check the django-example repo from Openshift. You have an example project from where you can get the project structure.
project
appname-1/
appname-2/
appname-n/
static/ # to store your static files
project/
wsgi.py # file created by django-admin startproject
templates/
wsgi/
static/ # in your settings.py set this folder as your STATIC_ROOT
manage.py
setup.py # file created by openshift python cartridge
wsgi.py # file created by openshift python cartridge
When you do a git push to your openshift remote, all of these files and folders will be created in $OPENSHIFT_REPO_DIR. The special folder $OPENSHIFT_REPO_DIR/wsgi/static is used to bypass wsgi and serve the files directly using apache. For this reason you must set this folder as your STATIC_ROOT to collect all of your static files.
Also for storing user uploaded files you should create a folder under $OPENSHIFT_DATA_DIR. For example, $OPENSHIFT_DATA_DIR/media. This folder will be persisted across future deploys.
If you use sqlite3 for you database your settings should be:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(os.getenv($OPENSHIFT_DATA_DIR), 'media'),
}
}

Acces image in folder without django collectstatic

I have a django web application which create screenshot calling an external python script.
But I'm concerned because every time I run the script I make a ./manage collectstatic to see the screenshots on my application. Soon I could have lots of collectstatic running simultaneously and it seems bad.
How can I have a folder where I can put the screens and then acces it with django without having to load it as a static file?
My current project looks like :
mysite
├── static
│ └── screenshots
| └── *.png
└── crowlers
├── wrapper.py
└── screenshot_robot.py
/opt/scripts/my_script.sh # launch wrapper.py and collectstatic
wrapper.py create .pngs in static/screenshots for my ./manage collectstatic to get them.
EDIT based on first answer:
I finally created a media directory at the root of my django project
Add the following in settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/'
In urls.py (To make it work with DEBUG=True when in developement state):
from django.conf import settings
## debug stuff to serve static media
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
static files are for your project's assets - css, js, images etc -, IOW things that are part of the project itself and you want to keep in your git/mercurial/whatever scc. Uploaded / dynamic /generated contents are supposed to go to the medias folder (settings.MEDIA_ROOT).

Categories

Resources