【问题标题】:django media not loadingdjango媒体没有加载
【发布时间】:2012-04-12 12:15:07
【问题描述】:

所以第一次使用 django 并遇到了媒体 url 不想加载/工作的问题,到目前为止我的 urls.py 是这样设置的

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

我的 settings.py 就像这样

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = 'http:/localhost:8000/admin-media/'

我的 html 模板是这样的

<link rel="stylesheet" href="/media/css/template.css" type="text/css" />
<link rel="stylesheet" href="/media/css/nivo-slider.css" type="text/css" />
<script type="text/javascript" src="/media/js/jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="/media/js/jquery.nivo.slider.pack.js"></script>

每当我输入http://localhost:8000/media/css/template.css 时,我都会得到

AttributeError at /media/css/template.css/

'str' object has no attribute 'resolve'

并在我的 django 服务器中记录以下内容

    Traceback (most recent call last):

  File "C:\Python27\lib\site-packages\django\core\servers\basehttp.py", line 283, in run
    self.result = application(self.environ, self.start_response)

  File "C:\Python27\lib\site-packages\django\core\handlers\wsgi.py", line 272, in __call__
    response = self.get_response(request)

  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 169, in get_response
    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 218, in handle_uncaught_exception
    return callback(request, **param_dict)

  File "C:\Python27\lib\site-packages\django\utils\decorators.py", line 93, in _wrapped_view
    response = view_func(request, *args, **kwargs)

  File "C:\Python27\lib\site-packages\django\views\defaults.py", line 30, in server_error
    t = loader.get_template(template_name) # You need to create a 500.html template.

  File "C:\Python27\lib\site-packages\django\template\loader.py", line 157, in get_template
    template, origin = find_template(template_name)

  File "C:\Python27\lib\site-packages\django\template\loader.py", line 138, in find_template
    raise TemplateDoesNotExist(name)

    TemplateDoesNotExist: 500.html

当我输入 http://localhost:8000/home/ 我的页面加载但我的 css 或 javascript 都没有加载..

【问题讨论】:

    标签: python django media django-urls django-settings


    【解决方案1】:

    如果您是第一次使用 Django,您应该使用 1.4。如果您使用的是较小的版本,请在继续之前升级。在旧版本的框架上开始一个新项目会在以后给你带来麻烦。

    所以,给定 Django 1.4。您需要以下(且仅以下):

    PROJECT_ROOT = os.path.dirname(__file__)
    
    MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
    MEDIA_URL = '/media/'
    
    STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
    STATIC_URL = '/static/'
    
    STATICFILES_DIRS = (
        os.path.join(PROJECT_ROOT, 'assets'),
    )
    

    PROJECT_ROOT 只是一个方便的变量以节省重复;它与 Django 没有任何关系。 “assets”目录是放置项目范围内所有静态资源的地方。您可以随意命名,但不能与MEDIA_ROOTSTATIC_ROOT 相同。

    另请注意:MEDIA_ROOT 现在仅用于上传,即通过FileFields 和ImageFields 在您的模型上添加的文件。 STATIC_ROOT 仅用于 collectstatic 管理命令的输出,您只能在生产中使用;你自己从来没有真正存储过任何东西。

    如果您在开发中使用runserver,Django 会自动为您提供所有静态资源。 仅当您在开发中使用另一个网络服务器时,您才需要将以下内容添加到 urls.py

    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    
    # ... the rest of your URLconf goes here ...
    
    urlpatterns += staticfiles_urlpatterns()
    

    最后,为了在开发中为您的MEDIA_ROOT 目录提供服务,请将以下内容添加到 urls.py:

    from django.conf import settings
    
    # ... the rest of your URLconf goes here ...
    
    if settings.DEBUG:
        urlpatterns += patterns('',
            url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
                'document_root': settings.MEDIA_ROOT,
            }),
       )
    

    在生产中,MEDIA_ROOTSTATIC_ROOT 都将直接由您的网络服务器提供服务,而不是 Django。

    见:https://docs.djangoproject.com/en/dev/howto/static-files/

    【讨论】:

      【解决方案2】:

      http://redsymbol.net/articles/django-attributeerror-str-object-no-attribute-resolve/

      假设你正在开发一个 Django 项目,使用它的开发网络 服务器,当您尝试在 浏览器:

      AttributeError: 'str' object has no attribute 'resolve'
      

      因为 你忘了输入“模式”这个词。

      具体来说,在某些 url.py 中,您输入了如下内容:

      urlpatterns = ('', (r'^$', direct_to_template, {'template':'a.html'}),
      
      # ... when you should have typed this:
      
      urlpatterns = patterns('', (r'^$', direct_to_template, {'template':'a.html'}),
      
      # ... See the difference?
      

      在第一个中,我是 错误地将 urlpatterns 分配为元组。第二个,我 正确使用 django.conf.urls.defaults.patterns 函数。

      【讨论】:

      • 这很奇怪,因为我的 urls.py 有以下 urlpatterns = patterns('', ('^home/$', master_page), ('^footer/$'), )
      【解决方案3】:

      我们这个代码

      urlpatterns += patterns('',
          (r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'media','show_indexes': True}),
          )
      

      【讨论】:

        猜你喜欢
        • 2018-12-09
        • 1970-01-01
        • 1970-01-01
        • 2022-06-13
        • 1970-01-01
        • 2022-11-10
        • 2012-10-03
        • 2011-08-06
        • 1970-01-01
        相关资源
        最近更新 更多