Using static files with the django virtual server

前端 未结 2 1930
無奈伤痛
無奈伤痛 2020-12-04 03:07

Questions exactly like this have been asked before, i\'ve read them all and tried to make sense of the official django documentation on the subject but i\'m still struggling

相关标签:
2条回答
  • 2020-12-04 03:32

    If you're using Django 1.4 then I would use the static tag:

    {% load static %}
    
    <link rel="stylesheet" href="{% static "CSS/base.css" %}" type="text/css" />
    

    You probably need this in your urls too, in development files are served via django

    if settings.DEBUG:
        urlpatterns += staticfiles_urlpatterns() #this serves static files and media files.
        #in case media is not served correctly
        urlpatterns += patterns('',
            url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
                'document_root': settings.MEDIA_ROOT,
                }),
        )
    

    Also in your settings it's common practice to avoid hardcoding locations, here's an example (by the way do you have the static filefinders in your settings?

    PROJECT_ROOT = path.dirname(path.abspath(__file__)) #gets directory settings is in
    
    STATIC_ROOT = path.join(PROJECT_ROOT,'static-root')
    # this folder is used to collect static files in production. not used in development
    
    STATIC_URL =  "/static/"
    
    STATICFILES_DIRS = (
        ('', path.join(PROJECT_ROOT,'static')), #store site-specific media here.
    )
    
    # List of finder classes that know how to find static files in
    # various locations.
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    )
    
    TEMPLATE_CONTEXT_PROCESSORS = (
        # other processors...
        "django.core.context_processors.static",
    )
    
    0 讨论(0)
  • 2020-12-04 03:34

    You should write your settings.py like that:

    import os
    PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    
    STATIC_URL = '/static/'  # Should be root relative or absolute
    
    STATICFILES_DIRS = (
        os.path.join(PROJECT_ROOT, 'static'),
    )
    
    # Where your static files will be collected with colletstatic command
    # I use it only in deployed configuration with DEBUG=False
    # Need to be outside STATICFILES_DIR
    STATIC_ROOT = '/var/www/your.site' 
    

    Just to be sure, check with Firebug or webkit debugger that CSS is loaded.

    Remember that Django won't serve your static files if settings.DEBUG == False.

    0 讨论(0)
提交回复
热议问题