Django 1.8: Help making filenames RELATIVE - python

I'm new to Django. First I'll explain my issue and my logic. I want to make my filepaths RELATIVE as opposed to the ABSOLUTE they are now so I can work on my laptop and PC and have everything show up as is.
I know I'll have to alter MEDIA_URL in the settings.py below. Does
MEDIA_URL = os.path.join(BASE_DIR, 'articles/static/articles/media/')
STATIC_URL = os.path.join(BASE_DIR, 'articles/static/')
make sense? I mean logically to me its saying from BASE_DIR which prints to C:\Users\kevIN3D\Documents\GitHub\articleTestProject\articleTestSite, would step into articles/static/articles/media/ or does the fact that
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
is abspath(...) change everything?
settings.py
"""
Django settings for articleTestSite project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
MEDIA_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/static/articles/'
MEDIA_URL = '/media/'
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '2u#9=qkari39(465g+u!2t7*9tt_pdv)%155jdgxnki5#jujje'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'articles',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'articleTestSite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'articleTestSite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC-5'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/'
STATIC_URL = '/static/'
urls.py
urlpatterns = [
url(r'^articles/', include('articles.urls')),
url(r'^$', HomePage.as_view(), name='home'),
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_ROOT)
My issue is when I try to use '/' in my declaration it prints out the filename as 'C:\Users\kevIN3D\Documents\GitHub\articleTestProject\articleTestSite\articles/static/' so it uses incorrect slashes for myself.
How do I go about making my page have relative filenames? I want to be able to work on this between my laptop and my PC, but as it currently stands I can only work on it on my PC because all the filenames are absolute and just give me broken links on my laptop.
Here is a link to the repository Github Repository. Please any help would be appreciated, I'm completely stumped. If someone could get that working, with images and custom CSS and then kind of walk me through what you did. Its my first time trying to distribute a Django file to more then just the local host.

Let me explain settings:
Right wave to separate the path
Pass every folder to the os.path.join() method. Example:
os.path.join(BASE_DIR, 'articles', 'static')
STATIC_URL, MEDIA_URL
This variables are passed to your template context proccessor (if you use django.template.context_processors.media) without any changes. This variables are used to make client-side links to your static and media content.
You should set your STATIC_URL and MEDIA_URL manually. Like that:
STATIC_URL = "/static/"
MEDIA_URL = "/media/"
Then you can use them in templates:
<img src="{{STATIC_URL}}img/logo.png">(...)
STATIC_ROOT, MEDIA_ROOT, STATICFILES_DIRS
STATIC_ROOT is used to bring all your static files in one place by collectstatic command (if you're using django simple server, you shouldn't care about it).
STATICFILES_DIRS is the folder when your django simple server (manage.py runserver command) gets files to serve. If you will run collectstatic command, evety file from every dir listed in STATICFILES_DIRS copied be moved in STATIC_ROOT.
MEDIA_ROOT is the folder where Django will hold user-uploaded files (ImageField, FileField)
You should use absolute path in STATIC_ROOT, MEDIA_ROOT, STATICFILES_DIRS:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'example', 'static', 'folder',)
Please note. If you have static folder in your app folder and your app is listed in INSTALLED_APPS this folder will be added to your STATICFILES_DIRS automatically.
Serving static and media files during development
It's really simple just add this lines after your urlpatterns:
urlpatterns = patterns('',
... your patterns...
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And don't forget to include settings:
from django.conf import settings
Serving on production server
Run collectstatic command to bring all your static content in one place.
Server your static and media folder using your apache/nginx/etc server:
Alias /media/ /path/to/your/media
Alias /static/ /path/to/your/static/

So I think I figured it out,
I was looking at things far to high-level so to speak. When in reality the answer was just simple. After giving myself a
print(BASE_DIR)
and having it spit out C:\Users\kevIN3D\Documents\GitHub\articlesTestProject\articleTestSite I realized all I needed to do was append that to my different ROOT variables.
MEDIA_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/static/articles/'
was my old MEDIA_ROOT, this was clearly absolute. BUT from this I can see that it shares that same filepath as BASE_DIR, so I went from there and
MEDIA_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/static/articles/'
became
MEDIA_ROOT = os.path.join(BASE_DIR, 'articles/static/articles/').replace('\\', '/') #run replace to convert UNIX slashes on Windows slashes
I had to do the same thing for STATIC_ROOT
STATIC_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/'
became
STATIC_ROOT = os.path.join(BASE_DIR, 'articles')

Related

Uploaded Media files are only served after I reload the django server

I'm quite new to django development, tired of searching for this particular case of mine.
I have django app running on my windows 10 with debug = False. I am just about to deploy my app to digital ocean droplet.
I am facing so many deployment and static + media file issues. I kind of figured out static files, they are fine, media files are also loaded.
But, when I upload a new image, access it directly, it says the resource I'm looking for isn't found. But it's 100% uploaded to media/images folder, and I can see it. Today, I think I found the some solution, I can access the media files only after I reload the django server. I want to know why is that?
My settings.py file
# Application definition
INSTALLED_APPS = [
'livereload',
'mnotes.apps.MnotesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'multiselectfield',
]
DJANGORESIZED_DEFAULT_SIZE = [100, 100]
DJANGORESIZED_DEFAULT_QUALITY = 75
DJANGORESIZED_DEFAULT_KEEP_META = True
DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'JPEG'
DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'JPEG': ".jpg"}
DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = True
CRISPY_TEMPLATE_PACK = 'bootstrap4'
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
'livereload.middleware.LiveReloadScript',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'MarketingNotes.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'MarketingNotes.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Seoul'
USE_I18N = True
USE_L10N = True
USE_TZ = False
SESSION_COOKIE_AGE = 60 * 60 * 24 * 30
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = ( 'static/', )
print(MEDIA_ROOT)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = 'login'
And my wsgi.py because I changed it with WhiteNoise app for serving static + media files
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MarketingNotes.settings')
application = get_wsgi_application()
from whitenoise import WhiteNoise
application = WhiteNoise(application, root='c:/Users/Peter/Django/MarketingNotes/mnotes/static')
application.add_files('c:/Users/Peter/Django/MarketingNotes/media', prefix='media/')
Then I tried to find some way of reloading the server when the user uploads an image, it kind of seems like a bad idea though, so, now, am I supposed to figure out some linux code to reload the gunicorn server in my droplet, or does django have anything to reload the server once the media folder is changed?
Sorry for my english
UPDATE
I found the solution, it was actually django problem, I saw in some post somebody say that django doesn't serve media files in production, and for serving media files I had to configure my nginx server. So I edited /etc/nginx/sites-enabled/myapp, added media there, and as soon as new files are uploaded, nginx is serving my media files.
Thank you all.
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Try to replace these settings in settings.py, if it doesn't works it means it's your IDE issue ..
It is related with Whitenoise.
Whitenoise only checks for static files at startup and so files added after the app starts won't be seen.
Since, Whitenose is not suitable for serving user-uploaded media files.
Please check Whitenose official docs.
http://whitenoise.evans.io/en/latest/django.html#serving-media-files

Deploy Django Static Files - Heroku

I am trying to deploy a Django site on Heroku, but I'm running into problems getting the app to locate my static files. I have used python manage.py collectstatic to collect my static files into a staticfiles folder, but my app still doesn't seem to be able to find them.
My settings.py looks like this:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = False
ALLOWED_HOSTS = ['www.tomdeldridge.com']
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'tomdeldridge.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['tomdeldridge/templates/tomdeldridge/'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'tomdeldridge.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATICFILES_DIRS = (
os.path.join(
os.path.dirname(__file__),
'static',
),
)
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
My wsgi.py file:
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tomdeldridge.settings")
My directory structure:
The images I'm trying to reference in my template definitely exist (they work fine when I run the app locally.) I reference them like this:
{% static 'tomdeldridge/images/computer-2.png' %}
But I get an error that looks something like this:
I'm not sure if I am referencing these paths properly during deployment though. The path's that are set to images/stylesheets/scripts in the code are using the path to the original static folder used in development. Do I have to rewrite all of those paths to point to the new staticfiles folder I created with the collectstatic command? That seems like an unnecessary hassle...
Or do I have to use a server like nginx to serve static files in deployment? I am totally lost on where to go from here, and I'm not really sure why it's necessary to reconfigure the entire static file structure just to deploy.
I'd rather add this as a comment but my karma prevents me from doing so;
My initial observation would be that the permissions aren't set correctly, so the server can't find the files correctly.
Do the files/folder have the same permissions as the development server?
One other question, does the os.path.dirname(__file__) correctly resolve to the project directory? Your BASE_DIRis referencing the same place, so try printing this on startup by putting:
print "BASE Directory:", BASE_DIR
On startup this should print out the directory its looking at as your project folder.
Check these both these things first and let me know the results of the above printout.
Edit, I'm not too familiar with Heroku but I'm starting with the basics (nima's solution below might work).

Static files not found - Deploying Django on Heroku

I am trying to deploy a Django site on Heroku, but I'm running into problems getting the app to locate my static files. I have used python manage.py collectstatic to collect my static files into a staticfiles folder, but my app still doesn't seem to be able to find them. I continue to get errors like this in my log:
I'm not sure if I am referencing the paths properly. The path's that are set to images/stylesheets/scripts in the code are using the path to the original static folder used in development. Do I have to rewrite all of those paths to point to the new staticfiles folder I created with the collectstatic command, or is there some other issue that could be causing this?
My settings.py looks like this:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = False
ALLOWED_HOSTS = ['www.tomdeldridge.com']
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'tomdeldridge.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['tomdeldridge/templates/tomdeldridge/'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'tomdeldridge.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATICFILES_DIRS = (
os.path.join(
os.path.dirname(__file__),
'static',
),
)
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
My wsgi.py file:
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tomdeldridge.settings")
My directory structure:
The images I'm trying to reference in my template definitely exist (they work fine when I run the app locally.) I reference them like this:
{% static 'tomdeldridge/images/computer-2.png' %}
Do I have to use a server like nginx to serve static files in deployment? I am totally lost on where to go from here, and I'm not really sure why it's necessary to reconfigure the entire static file structure just to deploy.
Install dj-static package
$ pip install dj-static
Configure your static assets in settings.py:
DEBUG = False
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
Then, update your wsgi.py file to use dj-static:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tomdeldridge.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())

css not loading in my login and admin page in django

I'm newbie in django and I started learning django with official tutorial.
I use django beside virtualenv, but I have a problem with
the login page and admin page because
they aren't load css and show login
page and admin page without any style
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'g8%o#ackd!hzekoho4rn7r7-t_m!sk$*nwi-4j556t=!ln3(#+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
First of all, Create folder named as "static", then you need to copy all the css/js file into static folder inside your project(or wherever you create static folder). Then declare the static files directory path in your settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = ('assets', BASE_DIR +'/static/',)
In your html file, add following line - {% load staticfiles %} at top of the header section or top of the file.
In <head> section you can link the css/js file using following code
<link rel="stylesheet" href="{% static 'assets/css/mystyle.css'%}">
</link>
<script src="{% static 'assets/js/jquery.js'%}"></script>
You need to read through the documentation for serving static files. When you are in production, your webserver (nginx/apache) would be responsible for serving static files such as JS, CSS and images. So any request for an image or JS file would be taken care of immediately by the webserver while any request for an actual page would be passed to your application server (i.e. Django)
In development you need to tell the development server to actually serve your static files so you need to add the following to your root urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
There are two situations that you maybe fail to load CSS files.
login Interceptor catch all the request, including your static files
browser cannot access your CSS files.
It is easy to judge what situation you are in. You can open your browser and check whether your CSS request is received. (for example, open your Chrome by F12 and check Console).
If there is not an error about failing to receive. Maybe your login Interceptor has caught all the things. And then, you can dig into what you received, at that you will find the answer. on my case, I find the response is my login page, not my ccs file.
You should let them go like this.
if static('') in request.path:
return self.get_response(request)
If received, you can see other answers.
(My English is not very good. If you want, you can edit this answer.)

Django Rest Framework - Missing Static Directory

I have recently started a Digital Ocean server with a pre-installed Django image on Ubuntu 14.04. I wanted to create an API, and have decided on the Django Rest Framework. I installed the Django Rest Framework exactly according to http://www.django-rest-framework.org/.
Here is what the tutorial site looks like when I access it on my server.
As you can see, it does not look like the site on the rest framework tutorial website. This is because of the fact that when I view the source code of my site, all of the /static/rest_framework/* files give me a 404 error.
Here is my settings.py file in the Django 'django_project' root directory.
"""
Django settings for django_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7Vnib8zBUEV3LfacGKi2rT185N36A8svyq8azJLvNpv7BxxzMK'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
)
REST_FRAMEWORK = {
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.HyperlinkedModelSerializer',
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'django_project.urls'
WSGI_APPLICATION = 'django_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django',
'USER': 'django',
'PASSWORD': 'yj4SM6qcP0',
'HOST': 'localhost',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
Can anyone help me fix this missing /static/rest_framework/ location error? If I am going to have an API for my application I would like it to be a good looking one.
Let me know if you need anything else to help you fix this, and thank you in advance for your help.
I have found the solution to my problem!
After much mind boggling research, I re-read this stack overflow question that didn't seem to help me the last time I took a look at it.
My new settings.py in my django_project folder now looks like this.
"""
Django settings for django_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'DwGCDqtcqzzGO2XK87u7bVSEUqHogZRFl4UdhkcCudSHxLUVvx'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
)
REST_FRAMEWORK = {
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.HyperlinkedModelSerializer',
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'django_project.urls'
WSGI_APPLICATION = 'django_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django',
'USER': 'django',
'PASSWORD': 'mpOQzpYFci',
'HOST': 'localhost',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_ROOT = '/home/django/django_project/django_project/static'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
I now have a folder named 'static' right next to my settings.py file in my django_project folder with all necessary resources such as 'rest_framework' and 'admin'. I restarted gunicorn after this change and reloaded my web page and it worked!
Thanks to those of you who tried to help, you did lead me in the right direction and probably made this go by a lot faster.
First, You need to set static url and static root in django settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
Then collect all static files
python manage.py collectstatic
In my case I was relying on Gunicorn to run the server.
I tried updating my settings.py file by following the above threads but unfortunately nothing seemed to work for me.
In the end I scratched my head around DRF docs specially this part https://docs.djangoproject.com/en/dev/howto/static-files/
I managed to solve this problem by updating by urls.py as following.
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Then updating my settings.py as follows.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
And now execute => python manage.py collectstatic
I did this tens of times and I was going insane over it. I had DEBUG = False.
If you're using Heroku to serve your website, try this link. It worked for me.
https://devcenter.heroku.com/articles/django-assets
In Summary:
Make a static folder if you don't have one already. (put it on the same level as your manage.py file)
Add the Python package to the folder (Copy this folder into the static folder --> C:\Python37_64\Lib\site-packages\rest_framework)
Add the code below to your project.
settings.py
...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
...
MIDDLEWARE_CLASSES = (
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
'whitenoise.middleware.WhiteNoiseMiddleware',
...
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
requirements.txt
...
#add whotrnoise to requirements
whitenoise
I had the same issue when I started learning python. I fixed by making below changes in settings.py of my project
DEBUG = True
I was unable to get any of the above solutions to work on our webapp, but discovered that if the app can connect to an S3 bucket where it can access deployed static files, django rest_framework works pretty seemlessly (as discussed here). Here's the relevant code for our settings.py:
aws = pcfenv.get_service(label='aws-s3') # or however you are accessing your s3 bucket & credentials
if aws is not None:
keys = aws.credentials
AWS_ACCESS_KEY_ID = keys["access_key_id"]
AWS_SECRET_ACCESS_KEY = keys["secret_access_key"]
AWS_STORAGE_BUCKET_NAME = keys["bucket"]
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_LOCATION = 'static'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
DEFAULT_FILE_STORAGE = 'mysite.storage_backends.MediaStorage'
# static files
STATIC_URL = '/static/'
STATIC_ROOT = 'static/'
# local storage
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/uploads/'
You'll need to pip install the boto3 and django-storages dependencies for it all to work.
you need both:
REST_FRAMEWORK = {
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.HyperlinkedModelSerializer',
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
and
the
python manage.py collectstatic
with the relevant directories set up.
the latter without the former won't do the work.
In debug mode, no changes are required.
If you are in a production environment, you need to set the static files point, usually set in nginx
location /static {
alias /<your app>/static; # your Django project's static files - amend as required
}

Categories

Resources