Unable to serve static files like css, js in django python

前端 未结 4 2327
轻奢々
轻奢々 2020-12-06 17:41

I am very new to django, and gone through tutorial for many days , i have started building a small website using django and trying to serve a css f

相关标签:
4条回答
  • 2020-12-06 18:13

    base.html

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

    settings

    PROJECT_DIR  = os.path.dirname(__file__) 
    
    MEDIA_ROOT = os.path.join(PROJECT_DIR,'media')
    MEDIA_URL = '/media/'
    STATIC_ROOT = os.path.join(PROJECT_DIR,'static')
    STATIC_URL = '/static/'
    
    STATICFILES_DIRS = (
        # Put strings here, like "/home/html/static" or "C:/www/django/static".
        # Always use forward slashes, even on Windows.
        # Don't forget to use absolute paths, not relative paths.
        os.path.join(PROJECT_DIR, 'staticfiles'),
    )
    

    url

    from django.conf.urls.defaults import *
    from django.conf import settings
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    from django.conf.urls.static import static
    from django.contrib import admin
    admin.autodiscover()
    
    urlpatterns = patterns('',
         url(r'^$', 'personnel_blog.views.home_page'),
         url(r'^admin/', include(admin.site.urls)),
    )+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
    urlpatterns += staticfiles_urlpatterns()
    
    0 讨论(0)
  • 2020-12-06 18:13

    Try changing your STATICFILES_DIRS setting to

    STATICFILES_DIRS = (
        os.path.join(PROJECT_DIR,'static'),
    )
    
    0 讨论(0)
  • 2020-12-06 18:14

    Your problem is related to this line:

    return render_to_response("home_page.html")
    

    Django's template engine requires two things to properly render a template.

    1. The template name
    2. A context variable

    The context variable is a key/value dictionary listing all of the variables available to the template.

    The render_to_response shortcut actually accepts two different context variable parameters.

    You're missing both.

    Without these variables, the template doesn't have ANY variables available to it. So your {{ STATIC_URL }} template variable is probably blank.

    To correct, try this:

    from django.shortcuts import render_to_response
    from django.template import RequestContext
    
    def home_page(request):
        return render_to_response("home_page.html", {}, context_instance=RequestContext(request))
    
    0 讨论(0)
  • 2020-12-06 18:36

    in settings.py try.

    PROJECT_DIR  = os.path.dirname(__file__)
    ...
    MEDIA_ROOT = os.path.join(PROJECT_DIR,'media')
    MEDIA_URL = '/media/'
    STATIC_ROOT = os.path.join(PROJECT_DIR,'static')
    STATIC_URL = '/static/'
    

    my settings.py file is usually in same directory as static directory

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