简体   繁体   中英

How can i serve static files in django?

I have a folder static :

static
-->css
----> main.css
-->images
----> image.png

Settings.py :

STATICFILES_DIRS=[
    os.path.join(BASE_DIR, "static"),
]

STATIC_URL = '/static/'

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

I ran collectstatic
Now I have in static_cdn : images , css and admin (never saw this last one before).
When I run my server, it still doesn't use static files.

Django doesn't serve static files in production but it keeps link to them. Here is where a django app called whitenoise comes to rescue when your debug is false on production. install whitenoise on your django app: pip install whitenoise then pip freeze > requirements.txt after this add this middleware to your django project settings

MIDDLEWARE = [
  # 'django.middleware.security.SecurityMiddleware',
  'whitenoise.middleware.WhiteNoiseMiddleware',
  # ...
]

then add this line

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

then push this code to your production server and make sure you run collectstatic command ie python manage.py collectstatic your static files now should be working.

Here is the common DigitalOcean solution:

Create a new space and connect to it eg via MobaXterm .

Then you have access to the file storage where you basically just run collectstatic within the manage.py directory.

Here is a official DigitalOcean Tutorial on deploying Django apps

You will need nginx when you deploy with DigitalOcean.

DigitalOcean spaces work with Amazon S3 Bucket behind the scenes, so you might directly set up a bucket and use this, but for me there is no benefit to go the hard way. Just use the DigitalOcean Space since this is perfectly linked to your droplet .

For storing static files in production, you're going to need something like S3 bucket or some other kind of external storage. I like to use whitenoise when I deploy to Heroku, since it's very simple to use. Here's an example of the configuration:

MIDDLEWARE = [
    # ...
    'whitenoise.middleware.WhiteNoiseMiddleware',

]

# ...

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'build/static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM