簡體   English   中英

在Django中設置靜態文件

[英]Setting up static files in Django

我在開發服務器上的Django項目中設置靜態文件時遇到問題。 我正在將Django-1.6.1與Python 2.7.5+一起使用。

我遵循了此鏈接中的說明: 管理靜態文件(CSS,圖像)

因此,我將django.contrib.staticfiles添加到INSTALLED_APPS

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'BlogContent',
)

我設置了STATIC_URL

STATIC_URL = '/static/'

我也將urls.py修改為:

urlpatterns = [           
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', home_view ),
    url(r'^about/$', about_view )
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

在模板中,我使用此標記:

{% load staticfiles %}
<img src="{% static "elo.jpg" %}"/>

並且所有文件都放入project_root / static /中,運行服務器后,我收到以下信息:

"GET /static/elo.jpg HTTP/1.1" 404 1625

您有任何解決方法的想法嗎? 預先感謝您的幫助。

Django本身不提供文件; 它將工作交給您選擇的任何Web服務器。 因此,請刪除urls.py中的+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 使用Apache2存儲您的靜態或媒體文件

https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/modwsgi/#serving-files

在您的Apache *.conf文件中(Apache 2.4)

<VirtualHost *:80>
        ServerName example.com
        ServerAdmin example@example.com

        Alias /media/ /home/tu/blog/media/
        Alias /static/ /home/tu/blog/collected_static/

        <Directory /home/tu/blog/media>
                Require all granted
        </Directory>

        <Directory /home/tu/blog/collected_static>
                Require all granted
        </Directory>

        WSGIScriptAlias / /home/tu/blog/blog/wsgi.py

        <Directory /home/tu/blog/blog>
        <Files wsgi.py>
                Require all granted
        </Files>
        </Directory>
</VirtualHost>

如果您使用Apache 2.2,請使用

Order allow,deny
Allow from all

代替

Require all granted

注意:您可以運行apachectl -v來查看您的Apache2版本

這是nginx配置的一個小片段,用於為應用程序(稱為APP)提供靜態文件和代理:

http {
…
    server {
        …
        location /static/ {
            autoindex on;
            alias /usr/share/nginx/html/static/;
        }

        location /APP {
            return 301 /APP/;
        }

        location /APP/ {
            rewrite ^/intranet(.*) /$1 break; 
            proxy_redirect off;
            proxy_pass http://127.0.0.1:8000;
        }
    }
}

請注意,我使用gunicornlocalhost:8000上運行我的應用程序,但是我使用http://localhost/APP連接到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM