404 Error for django serving static files. How to setup django to serve static files?

假装没事ソ 提交于 2019-11-29 23:31:38

问题


Settings.py file in Project directory :

I already added following :

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

-> in template

<script src="{% static "validateurl/home.js" %}"></script>

I have a directory static under project directory. home.js is under validateurl directory under static.

Referring JS File using following in template html file :

Please advise what am I missing here.

Errors below :


回答1:


Here are the steps to configure your django app to serve static files for local development.

The STATIC_ROOT default is None so you have to specify that in settings. Make sure you have something like this in your settings.py This tells your webserver where to find and serve the static file mapped to a url.

import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

Second also specify your STATIC_URL variable as it also defaults to none. following should suffice. This will be used for setting up the urlpattern.

STATIC_URL = '/static/'

You need to have a url pattern so your server knows what url corresponds to the static files

from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Specify STATICFILES_DIRS variable in settings. So that the collect static manager knows where to find statics and put them in the STATIC_ROOT. This can be an array or tuple of items to different directories. This can be empty if you have no additional directories

STATICFILES_DIRS =  (os.path.join(BASE_DIR, 'pathtohomejsdirectory/'),)

Finally, make sure you run python manage.py collectstatic This copies all the files specified in STATICFILES_DIRS over to the /static/ (STATIC_ROOT) directory to be served by django.

On a production, you want your webserver/reverse proxy say nginx or apache to serve the files. See here django documentation here



来源:https://stackoverflow.com/questions/52560619/404-error-for-django-serving-static-files-how-to-setup-django-to-serve-static-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!