Link stylesheets to Django template

℡╲_俬逩灬. 提交于 2019-12-07 07:28:49

问题


I have been looking at this tutorial and now have a stylesheet in /static/styles/.

The problem is that the template doesn't pick this up:

<html>
    <head>    
        <link rel="stylesheet" type="text/css" href="static/css/stylesheet.css" />
        <title>Search</title>
    </head>
    <body>
        ...

Do I need something in my settings file? Where am I going wrong?

My project structure is:

project
    - manage.py
    - project
        - static
        - templates
        -  __init__
        - etc..

EDIT My urls.py now looks like this:

from django.conf.urls import patterns, include, url
from bible import views
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'bible.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^verses/', views.search),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

And this is my view.py file

from django.http import HttpResponse, Http404
from django.shortcuts import render
from bible.models import TBbe, TBookNames


def search(request):
    errors = []
    if 'b' in request.GET:
        if 'c' in request.GET:
            if 'v' in request.GET:
                book = request.GET['b']
                chapter = request.GET['c']
                verse = request.GET['v']
                verses = TBbe.objects.filter(b=book, c=chapter, v=verse)
                book = TBookNames.objects.filter(id=book)
                books = TBookNames.objects.all;
                return render(request, 'verses.html', {'verses': verses, 'book': book, 'books':   books})
            else:
                raise Http404()
        else:
            raise Http404()
    else:
        books = TBookNames.objects.all;
        return render(request, 'search_verses.html', {'books': books})

回答1:


The problem seemed to be that I needed the following code in my settings.py file:

STATICFILES_DIRS = (
    os.path.join(os.path.dirname(__file__), 'static').replace('\\','/'),
)

which is the same as the code to reference my templates folder. If you put the static files at the same level, it should work. This is also providing you have followed the advice of everyone on here, importing static etc.




回答2:


  1. Make sure you have your static directory defined in your settings.py
  2. {% load staticfiles %}
  3. {% static 'css/mystyle.css' %} where you need the reference



回答3:


For a start, you should have a leading slash:

href="/static/css/stylesheet.css" 

but really you should use the static tag:

{% load static %}
...
href="{% static 'css/stylesheet.css' %}"


来源:https://stackoverflow.com/questions/26237563/link-stylesheets-to-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!