5

我正在使用 django 1.5

我能够在生产中提供文件,因为它是在 apache 级别处理的。这是我的 httpd.conf 文件:

<VirtualHost *:80>
WSGIScriptAlias / /home/membership/membership/wsgi.py

Alias /static/ "/home/membership/static/"


<Directory /home/membership/static>
Order deny,allow
Allow from all
</Directory>

<Directory "/usr/lib/python2.6/site-packages/django/contrib/admin/static/admin">
    Order deny,allow
    Allow from all
</Directory>

<Directory /home/membership/membership>
<Files wsgi.py>
Order deny,allow
Satisfy Any
Allow from all
</Files>
</Directory>
</VirtualHost>

这在生产中可以正常工作,因为Alias /static/ "/home/membership/static/"

当我尝试在本地开发环境中运行该应用程序时,我无法让它为静态文件提供服务,我只是得到一个页面未找到 404 错误。我猜这是因为当我在本地开发时,请求直接发送到开发服务器,因为没有使用 apache。

在此处输入图像描述

我在 /static/me.png 有一个文件。

我应该指定某个地方在开发中提供静态文件吗?

运行时python manage.py collectstatic,它似乎只收集管理应用程序的静态文件。我正在尝试提供的 /app/static 目录中直接有一个文件。

4

4 回答 4

14

如果您在开发期间提供静态文件

在您的settings.py文件中:

# Add it on your settings.py file
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"), # your static/ files folder
]

例子:

在此处输入图像描述

在您的根urls.py文件中:

# add these lines
from django.conf import settings
from django.conf.urls.static import static

# Add +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

例子:

在此处输入图像描述

这不适合生产使用!查看更多:https ://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-during-development

对于 media /目录中的媒体文件: https ://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user-during-development

于 2017-03-31T18:55:20.510 回答
11

您是否在站点设置中定义了静态文件的路径?我的意思不是 url /static/,我的意思是STATICFILES_DIR(它告诉你的开发服务器静态文件在哪里,就像配置文件告诉的一样apache

最好只遵循文档,这绝对是太棒了:

文档

于 2013-07-18T03:03:49.343 回答
4

在您的urls.py中,只需在底部添加:

if settings.DEBUG:
urlpatterns += patterns('',
    (r'^stati_directory/(?P<path>.*)$', 'django.views.static.serve',
    {'document_root':settings.STATIC_ROOT}),)

确保DEBUG = True

于 2013-07-18T03:03:29.430 回答
0

settings.py文件中更新以下行。

STATIC_URL = '/static/'
MEDIA_URL = '/static/media/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,’’)]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
  1. 在 static 中创建一个名为 media 的文件夹,并将所有媒体文件保存在其中。
  2. 运行python manage.py collectstatic以收集所有第三方应用程序静态文件,包括 django 管理静态文件。
  3. 在主要url.py添加以下行作为 url。

    from django.conf.urls.static import static
    from django.conf import settings
    
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
于 2016-08-31T06:36:11.467 回答