5

重複の可能性:
Djangoプロジェクト/アプリ内でCSSを整理してロードする方法は?

Djangoで静的ファイルを設定する方法についていくつかのWebサイトをフォローしています。これが私のステップです。

settings.pyを構成します。

STATIC_ROOT = '/Users/kin/mysite/static'
STATIC_URL = '/static/'

collectstaticコマンドを実行します。

python manage.py collectstatic

その後、画像ファイルがSTATIC_ROOTにコピーされているのを確認しました。

次に、テンプレートで、次の方法で画像ファイルを使用しようとします。

<img border="0" src="{{ STATIC_URL }}images.jpg" width="304" height="228">

しかし、ブラウザにロードすると画像が表示されません。ページのソースを確認しましたが、STATIC_URLが空のようです。

誰かがここで光を当てることができますか?

ありがとう

4

4 に答える 4

5

設定でパスをハードコーディングしないでください。私は通常、静的ファイルをメイン プロジェクトに配置するので、設定ファイルは次のようになります。

import os
MAIN_PROJECT = os.path.dirname(__file__)

それから

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
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(MAIN_PROJECT, 'static/'),
)

その後、{{ STATIC_URL }}ビューで使用できます

于 2013-01-22T07:40:33.483 に答える
4

実際、次のコードを使用するだけで正しくなりました。

{% load staticfiles %}
<img border="0" src="{% static 'image.jpg' %}" width="304" height="228">

これにより、STATIC_URL パスがレンダリングされます。

私を助けてくれてありがとう!

于 2013-01-22T07:43:28.673 に答える
1

でアプリを実行している場合python manage.py runserverは、url conf の末尾に次を追加する必要がある場合があります ( docsを参照)。

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns += staticfiles_urlpatterns()

django の開発サーバーで静的ファイルを提供するプロセスは、実動 Web サーバーでそれを行うプロセスとは異なります。

于 2013-01-22T07:30:35.733 に答える
0

あなたはこれで試すことができます

設定をインポートしurls.py て、以下のコードを urls.py に貼り付けます

if settings.DEBUG:
    urlpatterns += patterns('django.views.static',
    (r'^static_media/(?P<path>.*)$', 
        'serve', {
        'document_root': 'path/to/your/static/folder',
        'show_indexes': True }),)

今あなたのsettings.pyに行き、次のように設定を変更してください

MEDIA_URL = '/static_media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

次のように静的ファイルにアクセスします

<link rel="stylesheet" type="text/css" href="{{MEDIA_URL}}css/header.css" />
于 2013-01-22T07:34:56.133 に答える