how to use static folder in django for css and javascript?

后端 未结 3 1801
旧时难觅i
旧时难觅i 2021-01-14 15:46

I am new to django framework .I created simple welcome page now i want to include css file in my project.i cant apply css file in project .i got error like \"NetworkError: 4

3条回答
  •  孤城傲影
    2021-01-14 16:26

    Try doing a simple file like this

    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    OUTER_DIR = os.path.dirname(BASE_DIR)
    
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    )
    
    STATIC_URL = '/static/'
    
    TEMPLATE_DIRS=(
        os.path.join(OUTER_DIR, "static", "templates"),
    )
    
    MEDIA_URL='/media/'
    STATIC_ROOT = os.path.join(OUTER_DIR, "static", "static-only")
    MEDIA_ROOT = os.path.join(OUTER_DIR, "static", "media")
    
    STATICFILE_DIRS=(
        os.path.join(OUTER_DIR, "static"),
    )
    

    Then, in your code use {% static %} template tag.

    {% load staticfiles %}
    
    

    Test this out with

    DEBUG = True
    TEMPLATE_DEBUG = DEBUG
    

    If you turn off DEBUG then you need to add

    if not settings.DEBUG:
        urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
        urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
    

    Not when it's on as you have it now.

    The templates directory shouldn't be in the static folder though. In general the specific files needed for templates and static should be inside your Django project not separate.

提交回复
热议问题