How to use different staticfiles location based on if it is development or production server











up vote
0
down vote

favorite












This is my settings.py:



import os
import sys
SECRET_KEY = 'secrit'

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver')
if RUNNING_DEVSERVER:
DEBUG = True
else:
DEBUG = False

ALLOWED_HOSTS = ['127.0.0.1', 'ebdjangoapp-dev.us-east-1.elasticbeanstalk.com']


INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'ebdjangoapp',
'storages',
)


AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires
'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',
'Cache-Control': 'max-age=94608000',
}

AWS_STORAGE_BUCKET_NAME = 'ebdjangoappstaticfiles'
AWS_ACCESS_KEY_ID = 'key'
AWS_SECRET_ACCESS_KEY = 'secritkey'

# Tell django-storages that when coming up with the URL for an item in S3 storage, keep
# it simple - just use this domain plus the path. (If this isn't set, things get complicated).
# This controls how the `static` template tag from `staticfiles` gets expanded, if you're using it.
# We also use it in the next setting.
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

STATICFILES_LOCATION = 'static'

# This is used by the `static` template tag from `static`, if you're using that. Or if anything else
# refers directly to STATIC_URL. So it's safest to always set it.
if RUNNING_DEVSERVER:
STATIC_URL = '/static/'
else:
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)

# Tell the staticfiles app to use S3Boto storage when writing the collected static files (when
# you run `collectstatic`).
STATICFILES_STORAGE = 'ebdjangoapp.custom_storages.StaticStorage'

MEDIAFILES_LOCATION = 'media'
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
DEFAULT_FILE_STORAGE = 'ebdjangoapp.custom_storages.MediaStorage'


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 = 'ebdjango.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "ebdjangoapp/static/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 = 'ebdjango.wsgi.application'


if 'RDS_DB_NAME' in os.environ:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['RDS_DB_NAME'],
'USER': os.environ['RDS_USERNAME'],
'PASSWORD': os.environ['RDS_PASSWORD'],
'HOST': os.environ['RDS_HOSTNAME'],
'PORT': os.environ['RDS_PORT'],
}
}
else:
# Default Django
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

STATIC_ROOT = os.path.join(BASE_DIR, "static")


I follwed this URL https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ to let Amazon server my static and media files. It works perfectly on production. I decided to stop my production server until I fully test everything on development.



I thought these lines in my settings.py file:



RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver')
# ...
if RUNNING_DEVSERVER:
STATIC_URL = '/static/'
else:
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)


would allow my development server to look for static files in the static folder in the app directory. I did python manage.py runserver and went to 127.0.0.1 and when I inspect element, these errors are shown:



GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/js/home.js 
home:11 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/css/bootstrapCSS/css/bootstrap.min.css
home:12 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/js/bootstrapJS/bootstrap.min.js
home:15 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/css/home.css


When I try to import the CSS files I do it like this in my template:



{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'css/home.css' %}">


What else do I have to change so that it doesn't search https://ebdjangoappstaticfiles.s3.amazonaws.com for my static files?










share|improve this question




























    up vote
    0
    down vote

    favorite












    This is my settings.py:



    import os
    import sys
    SECRET_KEY = 'secrit'

    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver')
    if RUNNING_DEVSERVER:
    DEBUG = True
    else:
    DEBUG = False

    ALLOWED_HOSTS = ['127.0.0.1', 'ebdjangoapp-dev.us-east-1.elasticbeanstalk.com']


    INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'ebdjangoapp',
    'storages',
    )


    AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires
    'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',
    'Cache-Control': 'max-age=94608000',
    }

    AWS_STORAGE_BUCKET_NAME = 'ebdjangoappstaticfiles'
    AWS_ACCESS_KEY_ID = 'key'
    AWS_SECRET_ACCESS_KEY = 'secritkey'

    # Tell django-storages that when coming up with the URL for an item in S3 storage, keep
    # it simple - just use this domain plus the path. (If this isn't set, things get complicated).
    # This controls how the `static` template tag from `staticfiles` gets expanded, if you're using it.
    # We also use it in the next setting.
    AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

    STATICFILES_LOCATION = 'static'

    # This is used by the `static` template tag from `static`, if you're using that. Or if anything else
    # refers directly to STATIC_URL. So it's safest to always set it.
    if RUNNING_DEVSERVER:
    STATIC_URL = '/static/'
    else:
    STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)

    # Tell the staticfiles app to use S3Boto storage when writing the collected static files (when
    # you run `collectstatic`).
    STATICFILES_STORAGE = 'ebdjangoapp.custom_storages.StaticStorage'

    MEDIAFILES_LOCATION = 'media'
    MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
    DEFAULT_FILE_STORAGE = 'ebdjangoapp.custom_storages.MediaStorage'


    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 = 'ebdjango.urls'

    TEMPLATES = [
    {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, "ebdjangoapp/static/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 = 'ebdjango.wsgi.application'


    if 'RDS_DB_NAME' in os.environ:
    DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': os.environ['RDS_DB_NAME'],
    'USER': os.environ['RDS_USERNAME'],
    'PASSWORD': os.environ['RDS_PASSWORD'],
    'HOST': os.environ['RDS_HOSTNAME'],
    'PORT': os.environ['RDS_PORT'],
    }
    }
    else:
    # Default Django
    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

    STATIC_ROOT = os.path.join(BASE_DIR, "static")


    I follwed this URL https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ to let Amazon server my static and media files. It works perfectly on production. I decided to stop my production server until I fully test everything on development.



    I thought these lines in my settings.py file:



    RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver')
    # ...
    if RUNNING_DEVSERVER:
    STATIC_URL = '/static/'
    else:
    STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)


    would allow my development server to look for static files in the static folder in the app directory. I did python manage.py runserver and went to 127.0.0.1 and when I inspect element, these errors are shown:



    GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/js/home.js 
    home:11 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/css/bootstrapCSS/css/bootstrap.min.css
    home:12 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/js/bootstrapJS/bootstrap.min.js
    home:15 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/css/home.css


    When I try to import the CSS files I do it like this in my template:



    {% load staticfiles %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/home.css' %}">


    What else do I have to change so that it doesn't search https://ebdjangoappstaticfiles.s3.amazonaws.com for my static files?










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      This is my settings.py:



      import os
      import sys
      SECRET_KEY = 'secrit'

      BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

      RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver')
      if RUNNING_DEVSERVER:
      DEBUG = True
      else:
      DEBUG = False

      ALLOWED_HOSTS = ['127.0.0.1', 'ebdjangoapp-dev.us-east-1.elasticbeanstalk.com']


      INSTALLED_APPS = (
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      'rest_framework',
      'ebdjangoapp',
      'storages',
      )


      AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires
      'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',
      'Cache-Control': 'max-age=94608000',
      }

      AWS_STORAGE_BUCKET_NAME = 'ebdjangoappstaticfiles'
      AWS_ACCESS_KEY_ID = 'key'
      AWS_SECRET_ACCESS_KEY = 'secritkey'

      # Tell django-storages that when coming up with the URL for an item in S3 storage, keep
      # it simple - just use this domain plus the path. (If this isn't set, things get complicated).
      # This controls how the `static` template tag from `staticfiles` gets expanded, if you're using it.
      # We also use it in the next setting.
      AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

      STATICFILES_LOCATION = 'static'

      # This is used by the `static` template tag from `static`, if you're using that. Or if anything else
      # refers directly to STATIC_URL. So it's safest to always set it.
      if RUNNING_DEVSERVER:
      STATIC_URL = '/static/'
      else:
      STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)

      # Tell the staticfiles app to use S3Boto storage when writing the collected static files (when
      # you run `collectstatic`).
      STATICFILES_STORAGE = 'ebdjangoapp.custom_storages.StaticStorage'

      MEDIAFILES_LOCATION = 'media'
      MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
      DEFAULT_FILE_STORAGE = 'ebdjangoapp.custom_storages.MediaStorage'


      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 = 'ebdjango.urls'

      TEMPLATES = [
      {
      'BACKEND': 'django.template.backends.django.DjangoTemplates',
      'DIRS': [os.path.join(BASE_DIR, "ebdjangoapp/static/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 = 'ebdjango.wsgi.application'


      if 'RDS_DB_NAME' in os.environ:
      DATABASES = {
      'default': {
      'ENGINE': 'django.db.backends.postgresql_psycopg2',
      'NAME': os.environ['RDS_DB_NAME'],
      'USER': os.environ['RDS_USERNAME'],
      'PASSWORD': os.environ['RDS_PASSWORD'],
      'HOST': os.environ['RDS_HOSTNAME'],
      'PORT': os.environ['RDS_PORT'],
      }
      }
      else:
      # Default Django
      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

      STATIC_ROOT = os.path.join(BASE_DIR, "static")


      I follwed this URL https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ to let Amazon server my static and media files. It works perfectly on production. I decided to stop my production server until I fully test everything on development.



      I thought these lines in my settings.py file:



      RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver')
      # ...
      if RUNNING_DEVSERVER:
      STATIC_URL = '/static/'
      else:
      STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)


      would allow my development server to look for static files in the static folder in the app directory. I did python manage.py runserver and went to 127.0.0.1 and when I inspect element, these errors are shown:



      GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/js/home.js 
      home:11 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/css/bootstrapCSS/css/bootstrap.min.css
      home:12 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/js/bootstrapJS/bootstrap.min.js
      home:15 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/css/home.css


      When I try to import the CSS files I do it like this in my template:



      {% load staticfiles %}
      <link rel="stylesheet" type="text/css" href="{% static 'css/home.css' %}">


      What else do I have to change so that it doesn't search https://ebdjangoappstaticfiles.s3.amazonaws.com for my static files?










      share|improve this question















      This is my settings.py:



      import os
      import sys
      SECRET_KEY = 'secrit'

      BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

      RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver')
      if RUNNING_DEVSERVER:
      DEBUG = True
      else:
      DEBUG = False

      ALLOWED_HOSTS = ['127.0.0.1', 'ebdjangoapp-dev.us-east-1.elasticbeanstalk.com']


      INSTALLED_APPS = (
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      'rest_framework',
      'ebdjangoapp',
      'storages',
      )


      AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires
      'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',
      'Cache-Control': 'max-age=94608000',
      }

      AWS_STORAGE_BUCKET_NAME = 'ebdjangoappstaticfiles'
      AWS_ACCESS_KEY_ID = 'key'
      AWS_SECRET_ACCESS_KEY = 'secritkey'

      # Tell django-storages that when coming up with the URL for an item in S3 storage, keep
      # it simple - just use this domain plus the path. (If this isn't set, things get complicated).
      # This controls how the `static` template tag from `staticfiles` gets expanded, if you're using it.
      # We also use it in the next setting.
      AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

      STATICFILES_LOCATION = 'static'

      # This is used by the `static` template tag from `static`, if you're using that. Or if anything else
      # refers directly to STATIC_URL. So it's safest to always set it.
      if RUNNING_DEVSERVER:
      STATIC_URL = '/static/'
      else:
      STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)

      # Tell the staticfiles app to use S3Boto storage when writing the collected static files (when
      # you run `collectstatic`).
      STATICFILES_STORAGE = 'ebdjangoapp.custom_storages.StaticStorage'

      MEDIAFILES_LOCATION = 'media'
      MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
      DEFAULT_FILE_STORAGE = 'ebdjangoapp.custom_storages.MediaStorage'


      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 = 'ebdjango.urls'

      TEMPLATES = [
      {
      'BACKEND': 'django.template.backends.django.DjangoTemplates',
      'DIRS': [os.path.join(BASE_DIR, "ebdjangoapp/static/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 = 'ebdjango.wsgi.application'


      if 'RDS_DB_NAME' in os.environ:
      DATABASES = {
      'default': {
      'ENGINE': 'django.db.backends.postgresql_psycopg2',
      'NAME': os.environ['RDS_DB_NAME'],
      'USER': os.environ['RDS_USERNAME'],
      'PASSWORD': os.environ['RDS_PASSWORD'],
      'HOST': os.environ['RDS_HOSTNAME'],
      'PORT': os.environ['RDS_PORT'],
      }
      }
      else:
      # Default Django
      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

      STATIC_ROOT = os.path.join(BASE_DIR, "static")


      I follwed this URL https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ to let Amazon server my static and media files. It works perfectly on production. I decided to stop my production server until I fully test everything on development.



      I thought these lines in my settings.py file:



      RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver')
      # ...
      if RUNNING_DEVSERVER:
      STATIC_URL = '/static/'
      else:
      STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)


      would allow my development server to look for static files in the static folder in the app directory. I did python manage.py runserver and went to 127.0.0.1 and when I inspect element, these errors are shown:



      GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/js/home.js 
      home:11 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/css/bootstrapCSS/css/bootstrap.min.css
      home:12 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/js/bootstrapJS/bootstrap.min.js
      home:15 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/css/home.css


      When I try to import the CSS files I do it like this in my template:



      {% load staticfiles %}
      <link rel="stylesheet" type="text/css" href="{% static 'css/home.css' %}">


      What else do I have to change so that it doesn't search https://ebdjangoappstaticfiles.s3.amazonaws.com for my static files?







      django django-staticfiles






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 19 '17 at 23:36

























      asked Mar 19 '17 at 23:31









      user2719875

      4,4261456131




      4,4261456131
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          2
          down vote



          accepted










          You're on the right track with your if statement, however, your argv approach is very fragile. For example, you could run the same script with python manage.py runserver or manage.py runserver, changing the argument order and breaking your logic.



          Instead, there are two more sturdy approaches you can use; The easiest it to use the DEBUG setting to determine if you're in development or production.



          if DEBUG:
          # assume we're local
          else:
          # otherwise assume we're in production


          Then you just need to make sure you set DEBUG = False in production, which is something you should be very careful about doing anyways.



          If you have multiple environments, such as a QA server, staging server and production servers, it's wise to use an environment variable and import that into your settings.



          import os

          # get environment variable ENV from the system
          # default to prod if it doesn't exist
          ENV = os.getenv('ENV', 'prod')

          if ENV == 'local':
          # use local settings
          elif ENV == 'stage':
          # use staging settings
          else:
          # assume we're in prod


          You can then set the ENV environment variable in each of your environments to match their role (local, dev, qa, stage, prod, etc). This way you don't need to alter your settings files to flip variables.



          One last handy trick is you can cascade your settings files by selectively importing them based on a variable.



          ENV = os.getenv('ENV', 'prod')

          SOME_SETTING = 'no.png'

          if ENV == 'local':
          import settings_local # could override SOME_SETTING
          else:
          import settings_prod # could also override SOME_SETTING





          share|improve this answer























          • Okay thanks. So in my situation, how come it is still checking https://ebdjangoappstaticfiles.s3.amazonaws.com for static files even though I have if RUNNING_DEVSERVER: STATIC_URL = '/static/' (I also put a print('dev') statement inside the if statement and verified that it does enter the if statement).
            – user2719875
            Mar 19 '17 at 23:46












          • Your argv approach is very fragile since the arguments can change fairly easily python mange.py runserver vs manage.py runserver if you have python files automatically run. I've updated the answer with this info.
            – Soviut
            Mar 19 '17 at 23:49












          • Right, but I'll always be running the dev server with python manage.py runserver and if it is run in any other way, DEBUG will always be False. And since I don't run production with python manage.py runserver, I felt this is secure, right? But regarding the current issue, even though Django knows that I am running with dev server (or so I think, because I placed an if statement inside if RUNNING_DEVSERVER: STATIC_URL = '/static/' and it does get executed), it still checks https://ebdjangoappstaticfiles.s3.amazonaws.com for static files (instead of local files). Any idea why?
            – user2719875
            Mar 19 '17 at 23:54












          • It will break in all sorts of different ways, but if you insist on doing it that way, print sys.argv[1] to see what your settings file thinks the argument is. It most likely isn't picking it up correctly.
            – Soviut
            Mar 20 '17 at 0:14






          • 1




            Also, setting an environment variable is easy. It won't change how your production code runs since if the ENV variable is missing on the system it'll just default to prod.
            – Soviut
            Mar 20 '17 at 0:15


















          up vote
          0
          down vote













          You are on the right path. All you need to do is to set STATICFILES_STORAGE.



          if DEBUG:
          STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
          STATIC_URL = "/static/"
          else:
          STATICFILES_STORAGE = "backend.storage_backends.StaticStorage"
          STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION)





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f42893656%2fhow-to-use-different-staticfiles-location-based-on-if-it-is-development-or-produ%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            2
            down vote



            accepted










            You're on the right track with your if statement, however, your argv approach is very fragile. For example, you could run the same script with python manage.py runserver or manage.py runserver, changing the argument order and breaking your logic.



            Instead, there are two more sturdy approaches you can use; The easiest it to use the DEBUG setting to determine if you're in development or production.



            if DEBUG:
            # assume we're local
            else:
            # otherwise assume we're in production


            Then you just need to make sure you set DEBUG = False in production, which is something you should be very careful about doing anyways.



            If you have multiple environments, such as a QA server, staging server and production servers, it's wise to use an environment variable and import that into your settings.



            import os

            # get environment variable ENV from the system
            # default to prod if it doesn't exist
            ENV = os.getenv('ENV', 'prod')

            if ENV == 'local':
            # use local settings
            elif ENV == 'stage':
            # use staging settings
            else:
            # assume we're in prod


            You can then set the ENV environment variable in each of your environments to match their role (local, dev, qa, stage, prod, etc). This way you don't need to alter your settings files to flip variables.



            One last handy trick is you can cascade your settings files by selectively importing them based on a variable.



            ENV = os.getenv('ENV', 'prod')

            SOME_SETTING = 'no.png'

            if ENV == 'local':
            import settings_local # could override SOME_SETTING
            else:
            import settings_prod # could also override SOME_SETTING





            share|improve this answer























            • Okay thanks. So in my situation, how come it is still checking https://ebdjangoappstaticfiles.s3.amazonaws.com for static files even though I have if RUNNING_DEVSERVER: STATIC_URL = '/static/' (I also put a print('dev') statement inside the if statement and verified that it does enter the if statement).
              – user2719875
              Mar 19 '17 at 23:46












            • Your argv approach is very fragile since the arguments can change fairly easily python mange.py runserver vs manage.py runserver if you have python files automatically run. I've updated the answer with this info.
              – Soviut
              Mar 19 '17 at 23:49












            • Right, but I'll always be running the dev server with python manage.py runserver and if it is run in any other way, DEBUG will always be False. And since I don't run production with python manage.py runserver, I felt this is secure, right? But regarding the current issue, even though Django knows that I am running with dev server (or so I think, because I placed an if statement inside if RUNNING_DEVSERVER: STATIC_URL = '/static/' and it does get executed), it still checks https://ebdjangoappstaticfiles.s3.amazonaws.com for static files (instead of local files). Any idea why?
              – user2719875
              Mar 19 '17 at 23:54












            • It will break in all sorts of different ways, but if you insist on doing it that way, print sys.argv[1] to see what your settings file thinks the argument is. It most likely isn't picking it up correctly.
              – Soviut
              Mar 20 '17 at 0:14






            • 1




              Also, setting an environment variable is easy. It won't change how your production code runs since if the ENV variable is missing on the system it'll just default to prod.
              – Soviut
              Mar 20 '17 at 0:15















            up vote
            2
            down vote



            accepted










            You're on the right track with your if statement, however, your argv approach is very fragile. For example, you could run the same script with python manage.py runserver or manage.py runserver, changing the argument order and breaking your logic.



            Instead, there are two more sturdy approaches you can use; The easiest it to use the DEBUG setting to determine if you're in development or production.



            if DEBUG:
            # assume we're local
            else:
            # otherwise assume we're in production


            Then you just need to make sure you set DEBUG = False in production, which is something you should be very careful about doing anyways.



            If you have multiple environments, such as a QA server, staging server and production servers, it's wise to use an environment variable and import that into your settings.



            import os

            # get environment variable ENV from the system
            # default to prod if it doesn't exist
            ENV = os.getenv('ENV', 'prod')

            if ENV == 'local':
            # use local settings
            elif ENV == 'stage':
            # use staging settings
            else:
            # assume we're in prod


            You can then set the ENV environment variable in each of your environments to match their role (local, dev, qa, stage, prod, etc). This way you don't need to alter your settings files to flip variables.



            One last handy trick is you can cascade your settings files by selectively importing them based on a variable.



            ENV = os.getenv('ENV', 'prod')

            SOME_SETTING = 'no.png'

            if ENV == 'local':
            import settings_local # could override SOME_SETTING
            else:
            import settings_prod # could also override SOME_SETTING





            share|improve this answer























            • Okay thanks. So in my situation, how come it is still checking https://ebdjangoappstaticfiles.s3.amazonaws.com for static files even though I have if RUNNING_DEVSERVER: STATIC_URL = '/static/' (I also put a print('dev') statement inside the if statement and verified that it does enter the if statement).
              – user2719875
              Mar 19 '17 at 23:46












            • Your argv approach is very fragile since the arguments can change fairly easily python mange.py runserver vs manage.py runserver if you have python files automatically run. I've updated the answer with this info.
              – Soviut
              Mar 19 '17 at 23:49












            • Right, but I'll always be running the dev server with python manage.py runserver and if it is run in any other way, DEBUG will always be False. And since I don't run production with python manage.py runserver, I felt this is secure, right? But regarding the current issue, even though Django knows that I am running with dev server (or so I think, because I placed an if statement inside if RUNNING_DEVSERVER: STATIC_URL = '/static/' and it does get executed), it still checks https://ebdjangoappstaticfiles.s3.amazonaws.com for static files (instead of local files). Any idea why?
              – user2719875
              Mar 19 '17 at 23:54












            • It will break in all sorts of different ways, but if you insist on doing it that way, print sys.argv[1] to see what your settings file thinks the argument is. It most likely isn't picking it up correctly.
              – Soviut
              Mar 20 '17 at 0:14






            • 1




              Also, setting an environment variable is easy. It won't change how your production code runs since if the ENV variable is missing on the system it'll just default to prod.
              – Soviut
              Mar 20 '17 at 0:15













            up vote
            2
            down vote



            accepted







            up vote
            2
            down vote



            accepted






            You're on the right track with your if statement, however, your argv approach is very fragile. For example, you could run the same script with python manage.py runserver or manage.py runserver, changing the argument order and breaking your logic.



            Instead, there are two more sturdy approaches you can use; The easiest it to use the DEBUG setting to determine if you're in development or production.



            if DEBUG:
            # assume we're local
            else:
            # otherwise assume we're in production


            Then you just need to make sure you set DEBUG = False in production, which is something you should be very careful about doing anyways.



            If you have multiple environments, such as a QA server, staging server and production servers, it's wise to use an environment variable and import that into your settings.



            import os

            # get environment variable ENV from the system
            # default to prod if it doesn't exist
            ENV = os.getenv('ENV', 'prod')

            if ENV == 'local':
            # use local settings
            elif ENV == 'stage':
            # use staging settings
            else:
            # assume we're in prod


            You can then set the ENV environment variable in each of your environments to match their role (local, dev, qa, stage, prod, etc). This way you don't need to alter your settings files to flip variables.



            One last handy trick is you can cascade your settings files by selectively importing them based on a variable.



            ENV = os.getenv('ENV', 'prod')

            SOME_SETTING = 'no.png'

            if ENV == 'local':
            import settings_local # could override SOME_SETTING
            else:
            import settings_prod # could also override SOME_SETTING





            share|improve this answer














            You're on the right track with your if statement, however, your argv approach is very fragile. For example, you could run the same script with python manage.py runserver or manage.py runserver, changing the argument order and breaking your logic.



            Instead, there are two more sturdy approaches you can use; The easiest it to use the DEBUG setting to determine if you're in development or production.



            if DEBUG:
            # assume we're local
            else:
            # otherwise assume we're in production


            Then you just need to make sure you set DEBUG = False in production, which is something you should be very careful about doing anyways.



            If you have multiple environments, such as a QA server, staging server and production servers, it's wise to use an environment variable and import that into your settings.



            import os

            # get environment variable ENV from the system
            # default to prod if it doesn't exist
            ENV = os.getenv('ENV', 'prod')

            if ENV == 'local':
            # use local settings
            elif ENV == 'stage':
            # use staging settings
            else:
            # assume we're in prod


            You can then set the ENV environment variable in each of your environments to match their role (local, dev, qa, stage, prod, etc). This way you don't need to alter your settings files to flip variables.



            One last handy trick is you can cascade your settings files by selectively importing them based on a variable.



            ENV = os.getenv('ENV', 'prod')

            SOME_SETTING = 'no.png'

            if ENV == 'local':
            import settings_local # could override SOME_SETTING
            else:
            import settings_prod # could also override SOME_SETTING






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 19 '17 at 23:46

























            answered Mar 19 '17 at 23:39









            Soviut

            56.5k33142208




            56.5k33142208












            • Okay thanks. So in my situation, how come it is still checking https://ebdjangoappstaticfiles.s3.amazonaws.com for static files even though I have if RUNNING_DEVSERVER: STATIC_URL = '/static/' (I also put a print('dev') statement inside the if statement and verified that it does enter the if statement).
              – user2719875
              Mar 19 '17 at 23:46












            • Your argv approach is very fragile since the arguments can change fairly easily python mange.py runserver vs manage.py runserver if you have python files automatically run. I've updated the answer with this info.
              – Soviut
              Mar 19 '17 at 23:49












            • Right, but I'll always be running the dev server with python manage.py runserver and if it is run in any other way, DEBUG will always be False. And since I don't run production with python manage.py runserver, I felt this is secure, right? But regarding the current issue, even though Django knows that I am running with dev server (or so I think, because I placed an if statement inside if RUNNING_DEVSERVER: STATIC_URL = '/static/' and it does get executed), it still checks https://ebdjangoappstaticfiles.s3.amazonaws.com for static files (instead of local files). Any idea why?
              – user2719875
              Mar 19 '17 at 23:54












            • It will break in all sorts of different ways, but if you insist on doing it that way, print sys.argv[1] to see what your settings file thinks the argument is. It most likely isn't picking it up correctly.
              – Soviut
              Mar 20 '17 at 0:14






            • 1




              Also, setting an environment variable is easy. It won't change how your production code runs since if the ENV variable is missing on the system it'll just default to prod.
              – Soviut
              Mar 20 '17 at 0:15


















            • Okay thanks. So in my situation, how come it is still checking https://ebdjangoappstaticfiles.s3.amazonaws.com for static files even though I have if RUNNING_DEVSERVER: STATIC_URL = '/static/' (I also put a print('dev') statement inside the if statement and verified that it does enter the if statement).
              – user2719875
              Mar 19 '17 at 23:46












            • Your argv approach is very fragile since the arguments can change fairly easily python mange.py runserver vs manage.py runserver if you have python files automatically run. I've updated the answer with this info.
              – Soviut
              Mar 19 '17 at 23:49












            • Right, but I'll always be running the dev server with python manage.py runserver and if it is run in any other way, DEBUG will always be False. And since I don't run production with python manage.py runserver, I felt this is secure, right? But regarding the current issue, even though Django knows that I am running with dev server (or so I think, because I placed an if statement inside if RUNNING_DEVSERVER: STATIC_URL = '/static/' and it does get executed), it still checks https://ebdjangoappstaticfiles.s3.amazonaws.com for static files (instead of local files). Any idea why?
              – user2719875
              Mar 19 '17 at 23:54












            • It will break in all sorts of different ways, but if you insist on doing it that way, print sys.argv[1] to see what your settings file thinks the argument is. It most likely isn't picking it up correctly.
              – Soviut
              Mar 20 '17 at 0:14






            • 1




              Also, setting an environment variable is easy. It won't change how your production code runs since if the ENV variable is missing on the system it'll just default to prod.
              – Soviut
              Mar 20 '17 at 0:15
















            Okay thanks. So in my situation, how come it is still checking https://ebdjangoappstaticfiles.s3.amazonaws.com for static files even though I have if RUNNING_DEVSERVER: STATIC_URL = '/static/' (I also put a print('dev') statement inside the if statement and verified that it does enter the if statement).
            – user2719875
            Mar 19 '17 at 23:46






            Okay thanks. So in my situation, how come it is still checking https://ebdjangoappstaticfiles.s3.amazonaws.com for static files even though I have if RUNNING_DEVSERVER: STATIC_URL = '/static/' (I also put a print('dev') statement inside the if statement and verified that it does enter the if statement).
            – user2719875
            Mar 19 '17 at 23:46














            Your argv approach is very fragile since the arguments can change fairly easily python mange.py runserver vs manage.py runserver if you have python files automatically run. I've updated the answer with this info.
            – Soviut
            Mar 19 '17 at 23:49






            Your argv approach is very fragile since the arguments can change fairly easily python mange.py runserver vs manage.py runserver if you have python files automatically run. I've updated the answer with this info.
            – Soviut
            Mar 19 '17 at 23:49














            Right, but I'll always be running the dev server with python manage.py runserver and if it is run in any other way, DEBUG will always be False. And since I don't run production with python manage.py runserver, I felt this is secure, right? But regarding the current issue, even though Django knows that I am running with dev server (or so I think, because I placed an if statement inside if RUNNING_DEVSERVER: STATIC_URL = '/static/' and it does get executed), it still checks https://ebdjangoappstaticfiles.s3.amazonaws.com for static files (instead of local files). Any idea why?
            – user2719875
            Mar 19 '17 at 23:54






            Right, but I'll always be running the dev server with python manage.py runserver and if it is run in any other way, DEBUG will always be False. And since I don't run production with python manage.py runserver, I felt this is secure, right? But regarding the current issue, even though Django knows that I am running with dev server (or so I think, because I placed an if statement inside if RUNNING_DEVSERVER: STATIC_URL = '/static/' and it does get executed), it still checks https://ebdjangoappstaticfiles.s3.amazonaws.com for static files (instead of local files). Any idea why?
            – user2719875
            Mar 19 '17 at 23:54














            It will break in all sorts of different ways, but if you insist on doing it that way, print sys.argv[1] to see what your settings file thinks the argument is. It most likely isn't picking it up correctly.
            – Soviut
            Mar 20 '17 at 0:14




            It will break in all sorts of different ways, but if you insist on doing it that way, print sys.argv[1] to see what your settings file thinks the argument is. It most likely isn't picking it up correctly.
            – Soviut
            Mar 20 '17 at 0:14




            1




            1




            Also, setting an environment variable is easy. It won't change how your production code runs since if the ENV variable is missing on the system it'll just default to prod.
            – Soviut
            Mar 20 '17 at 0:15




            Also, setting an environment variable is easy. It won't change how your production code runs since if the ENV variable is missing on the system it'll just default to prod.
            – Soviut
            Mar 20 '17 at 0:15












            up vote
            0
            down vote













            You are on the right path. All you need to do is to set STATICFILES_STORAGE.



            if DEBUG:
            STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
            STATIC_URL = "/static/"
            else:
            STATICFILES_STORAGE = "backend.storage_backends.StaticStorage"
            STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION)





            share|improve this answer

























              up vote
              0
              down vote













              You are on the right path. All you need to do is to set STATICFILES_STORAGE.



              if DEBUG:
              STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
              STATIC_URL = "/static/"
              else:
              STATICFILES_STORAGE = "backend.storage_backends.StaticStorage"
              STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION)





              share|improve this answer























                up vote
                0
                down vote










                up vote
                0
                down vote









                You are on the right path. All you need to do is to set STATICFILES_STORAGE.



                if DEBUG:
                STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
                STATIC_URL = "/static/"
                else:
                STATICFILES_STORAGE = "backend.storage_backends.StaticStorage"
                STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION)





                share|improve this answer












                You are on the right path. All you need to do is to set STATICFILES_STORAGE.



                if DEBUG:
                STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
                STATIC_URL = "/static/"
                else:
                STATICFILES_STORAGE = "backend.storage_backends.StaticStorage"
                STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION)






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 11 at 3:48









                m4rko

                165




                165






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f42893656%2fhow-to-use-different-staticfiles-location-based-on-if-it-is-development-or-produ%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Florida Star v. B. J. F.

                    Danny Elfman

                    Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues