Django - referencing static files in templates

后端 未结 3 1218
深忆病人
深忆病人 2020-12-17 18:05

I\'m having difficulty referencing static files in my templates. I am using Twitter Bootstrap and have the bootstrap files (css, img, js) sitting at mysite/static.

相关标签:
3条回答
  • 2020-12-17 18:40

    When you set static_root, for example:

    STATIC_ROOT = os.path.join(BASE_DIR, "static_root/")
    

    , all files are copied there, instead of in project_root/static. It is a new mechanism introduced in Django 1.3, to easy the static file processing: it will collect all files in each STATICFILES_DIR and all static dir under each installed app, so you copy them once in all.

    Refer the css/js files with static_root path.

    0 讨论(0)
  • 2020-12-17 18:45

    It should be

    {% load static %}
    

    And then something like

    <!-- path -->
    <link href="{% static 'bootstrap/css/bootstrap.css' %}" rel="stylesheet" type="text/css">
    <!--->
    

    Update for Completeness

    Folder Structure

    • proj
    • app1
    • app2
    • myproj_public
    • static
      • css
        • bootstrap.css
      • js
        • xyz.js

    Settings File

    STATIC_ROOT = os.path.join(os.path.abspath(
        os.path.join(PROJECT_ROOT, 'myproj_public', 'static')), '')
    
    STATIC_URL = '/static/'
    
    0 讨论(0)
  • 2020-12-17 18:55

    Are you setting the user_stylesheet context variable in your view? You need to set that before you can pass it onto templates.

    I usually just use the {{ static_url }} tag for doing this stuff, so my code for including bootstrap components would be like.

    <link href="{{ STATIC_URL }}bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <script src="{{ STATIC_URL }}bootstrap/js/jquery.js"></script>
    

    Assuming that bootstrap folder is present inside static.

    EDIT

    For your case, to set user_stylesheet context variable, you'll need to do something like

    dict["user_stylesheet"]= <path to your file>
    #add other context variables you might have to
    render_to_response(<your template name>, dict, context_instance=RequestContext(request))
    
    0 讨论(0)
提交回复
热议问题