django not serving static files

前端 未结 3 918
悲&欢浪女
悲&欢浪女 2020-12-21 00:13

I\'m using Django==1.5.5 and My django app is structured as

--project/
----project/
------settings.py
------urls.py
----app1/
------models.py
--         


        
相关标签:
3条回答
  • 2020-12-21 00:58

    I had the same problem and none of the answers I found worked. It turns out that there are a few parts that must be set up correctly for static files to work. Note: I'm using django 1.6 and this solution is for development not deployment.

    Setting up static file dirs

    django-admin.py startproject $site_name
    mkdir $site_name/static
    mkdir $site_name/static/css
    mkdir $site_name/static/javascript
    mkdir $site_name/static/images
    

    your folder should look like this

    $site_name/
        manage.py
        $site_name/
            __init__.py
            settings.py
            urls.py
            wsgi.py
        static/
            css/
            javascript
            images/
    

    edit the $site_name/$site_name/setting.py file and add

    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')
    STATICFILES_DIRS =( os.path.join(STATIC_ROOT, 'css/'),
                        os.path.join(STATIC_ROOT, 'javascript/'),
                        os.path.join(STATIC_ROOT, 'images/')
                      )
    

    edit $site_name/$site_name/urls.py and add

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    

    using static urls

    {% load staticfiles %}
    <a href="{% static "banner.png" %}">
    
    0 讨论(0)
  • 2020-12-21 00:59

    According to docs right way to load static file is

    {% load staticfiles %}
    <img src="{% static 'my_app/myexample.jpg' %}" alt="My image"/>
    

    This will work

    0 讨论(0)
  • 2020-12-21 01:07

    Only for development. Set DEBUG = True in settings.py file and add 'django.contrib.staticfiles' in INSTALLED_APPS. Next, add these lines of code to settings.py file of your project:

    STATIC_URL = '/static/'
    STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
    
    0 讨论(0)
提交回复
热议问题