0

我知道有很多关于 Django 模板图像的现有问题,但我似乎无法让我的工作。我目前在我的项目中有一个应用程序,并且有一个静态文件夹结构,看起来像

    djangoproject/appname/static/images/ 

在同一个 django app 的 templates 文件夹中,我有各种 HTML 文件,需要引用上面显示的文件夹中的图像。在我的settings.py文件夹中,我有

    STATIC_ROOT=''
    STATIC_URL = 'appname/static/' 
    STATICFILES_DIRS = ( 
    ) 
    TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',

)

在我的模板文件中,我有

    <a href="AddTransaction.html"><img id="btnTransaction" src="{{ STATIC_URL }}images/btnTransaction.png"/></a>

当我运行开发服务器时,它一直在寻找appname/images/btnTransaction.png图像。

我怎样才能解决这个问题?

4

4 回答 4

1

摆脱 appname 并更改为STATIC_URL= '/static/'

于 2012-05-09T05:29:03.293 回答
1

In the STATIC_FILES_DIR tuple, you need to have a string that is the absolute path to the static directory on your machine. So if you're *nix it would be '/User/path/to/django/static/dir/' or 'C:/path/to/django/static/dir/' if you're on Windows.

STATIC_URL, like you see here, is whatever will be output in the HTML and is meant for the absolute path of an image relative to the browser. You could do 'http://127.0.0.1:8000/static/' if you're running locally or something like 'http://mydomain.com/static/' if in production or something like 'http://static.mydomain.com/static/' if you have a CDN or just '/static/' to work for all (if you're using the same host for your static files and app).

于 2012-05-09T03:11:17.507 回答
1

you want the path to the images to be in a web accessible location, something away from django and your app (unless you're adding access controls, then you'll need a separate function in your views to handle that). Thing is, the img tag's src is not pulling the image in when the template is rendered server side, but in the client and the client makes a separate request for the image. If the image can't be found by the url, then it won't get shown.

于 2012-05-09T03:11:52.130 回答
0

而不是使用“静态”使用“媒体”

像这样

设置.py

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/Users/YOUR USERNAME/djcode/blankpage/media/'

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

并在 urls.py

url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root':  settings.MEDIA_ROOT}),

在您的模板中引用您的文件,如下所示

href="/media/styles/profile.css"
于 2012-05-09T15:28:26.013 回答