Sven
Sven

Reputation: 1107

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.
How can I serve my static files to my server without using apache or nginx or that kind of stuff?

Upvotes: 1

Views: 533

Answers (3)

JSRB
JSRB

Reputation: 2613

Here is the common DigitalOcean solution:

Create a new space and connect to it e.g. 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.

Upvotes: 1

Nischal Shrestha
Nischal Shrestha

Reputation: 119

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 i.e python manage.py collectstatic your static files now should be working.

Upvotes: 1

martin
martin

Reputation: 885

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'

Upvotes: 0

Related Questions