标签: django-staticfiles

django {{STATIC_URL}}有时不起作用

一个可怜的django初学者在一些视图上访问静态文件(css,js)时遇到阻塞问题.主要是,在主页上这些静态文件是完全可访问的,但在不同的页面上,它没有,并且布局完全被破坏.

这是我的settings.py:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'bands',
    'lyrics',
    'articles',
)
PROJECT_DIR = os.path.dirname(__file__)
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, "static"),
)
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Run Code Online (Sandbox Code Playgroud)

这是我的基本通用模板的一部分,其中包含视图扩展:

<link rel="Shortcut icon" href="{{ STATIC_URL }}img/favicon32.png" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/bootstrap.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/sortable.js"></script>
Run Code Online (Sandbox Code Playgroud)

渲染时,它会返回这样的代码(这就是我想要的):

<link rel="Shortcut icon" href="/static/img/favicon32.png" />
<link rel="stylesheet" type="text/css" href="/static/css/bootstrap.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<script type="text/javascript" …
Run Code Online (Sandbox Code Playgroud)

django configuration django-staticfiles

4
推荐指数
1
解决办法
673
查看次数

使用{%static%}进行Django压缩

我正在努力使django压缩工作,但我相信它不起作用因为我的{% static %}使用.

我的模板是(我正在使用pyjade,但无关紧要):

- load staticfiles
- load compress

| {% compress css %}
link(rel="stylesheet", href="{% static 'less/bootstrap.css' %} ")
link(rel="stylesheet", href="{% static 'timepicker/css/bootstrap-timepicker.min.css'%}")
link(rel="stylesheet", href="{% static 'leaflet/addons/locatecontrol/L.Control.Locate.css' %} ")
link(rel="stylesheet", href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css")
link(href='//api.tiles.mapbox.com/mapbox.js/v1.3.1/mapbox.css', rel='stylesheet')
| {% endcompress %}
Run Code Online (Sandbox Code Playgroud)

还是我的settings.py的一部分:

PROJECT_DIR = os.path.dirname(os.path.realpath(__file__))

STATIC_ROOT = os.path.join(PROJECT_DIR, '../static')
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'media'),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #'django.contrib.staticfiles.finders.DefaultStorageFinder',
    'compressor.finders.CompressorFinder',
)

COMPRESS_URL = STATIC_URL
COMPRESS_ROOT = STATIC_ROOT
COMPRESS_STORAGE = "staticfiles.storage.StaticFileStorage"

INSTALLED_APPS = (....,'compressor',....)
Run Code Online (Sandbox Code Playgroud)

即使我$ …

django django-static django-staticfiles django-compressor

4
推荐指数
1
解决办法
3810
查看次数

django admin 静态服务地址错误

我有一个奇怪的问题 - 我的开发服务器试图通过使用错误的网址来提供管理静态服务。

使用 Django 1.6

我的主要 urlconf

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
   url(r'^admin/', include(admin.site.urls)),
   url(r'^$', include('dash.urls')),
   )


urlpatterns += staticfiles_urlpatterns()
Run Code Online (Sandbox Code Playgroud)

设置就像

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
locale = lambda path: os.path.join(BASE_DIR, path)
STATIC_URL = "static/"
MEDIA_URL = "media/"
STATIC_ROOT = locale("static")
MEDIA_ROOT = locale("media")
Run Code Online (Sandbox Code Playgroud)

应用

INSTALLED_APPS = (
  'django.contrib.staticfiles',
  'django.contrib.admin',
)
Run Code Online (Sandbox Code Playgroud)

奇怪的是,我的自定义应用程序通过像 localhost:8000/static/css/blah 这样的 url 通常提供静态服务

但管理员使用

[2013年11月24日18:47:41]“获取/admin/static/admin/css/base.css HTTP/1.1”404 4316

各位,说真的,前缀 /admin/static 的起源是什么?0_o 我不使用 ADMIN_MEDIA_PREFIX 等已弃用的内容。

基本管理模板使用 {% static "admin/css/base.css" %} 标签,其代码为

from django.conf import settings
from django.template …
Run Code Online (Sandbox Code Playgroud)

python django django-templates django-admin django-staticfiles

4
推荐指数
1
解决办法
3745
查看次数

Django 1.8和令人困惑的"静态文件"

我已经启动了一个新的Django 1.8项目,并试图在开发环境中提供静态文件.我很确定我明确地遵循了文档,但它只是不起作用.

Settings.py

STATICFILES_DIR = (                                                                 
  os.path.join(BASE_DIR, 'static/'),                                                
  BASE_DIR                                                                          
)                                                                                                                                                                 

STATIC_URL = '/static/'                                                             
STATIC_ROOT = '/srv/www/cpm2/static/'    
Run Code Online (Sandbox Code Playgroud)

urls.py:

from django.conf.urls import include, patterns, url 
from django.conf import settings
from django.conf.urls.static import static·
from django.contrib import admin
from django.views.generic import TemplateView

urlpatterns = [ 
    url(r'^admin/', include(admin.site.urls)),
    url(r'^test/', TemplateView.as_view(template_name="basics/base.html")),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Run Code Online (Sandbox Code Playgroud)

templates/basics/base.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">


    {% load staticfiles %}
    <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">

  </head>


  <body>
      <h1>Hello, …
Run Code Online (Sandbox Code Playgroud)

django django-staticfiles

4
推荐指数
1
解决办法
3407
查看次数

从 Google Cloud Storage Bucket 提供静态文件(适用于托管在 GCE 上的 Django 应用程序)

我正在尝试从 Cloud Storage Bucket 为我的 django 应用程序提供静态文件,但不知道确切的过程。有人可以建议这样做的正确方法吗?

我做的步骤:

  1. 使用 gsutil 命令上传 Google Cloud Storage Bucket(www.example.com) 上的所有静态文件。
  2. 编辑的/etc/apache2/sites-available/default-ssl.conf文件。

文件内容:

<VirtualHost *:443>
        ServerName example.com
        ServerAdmin admin@example.com

 #       Alias /static /opt/projects/example-google/example_static
        Alias /static https://storage.googleapis.com/www.example.com/static
        <Directory /opt/projects/example-google/example_static>
           Require all granted
        </Directory>

        <Directory /opt/projects/example-google/example/example>
            <Files wsgi.py>
                Require all granted
            </Files>
        </Directory>

        WSGIDaemonProcess example python-path=/opt/projects/example-google/example:/opt/projects/example-google/venv/lib/python2.7/site-packages
        WSGIProcessGroup example
WSGIApplicationGroup %{GLOBAL}
        WSGIScriptAlias / /opt/projects/example-google/example/example/wsgi.py

        SSLEngine on
        SSLCertificateFile  /etc/apache2/ssl/example.com.crt
        SSLCertificateKeyFile /etc/apache2/ssl/example.com.key
        SSLCertificateChainFile /etc/apache2/ssl/intermediate.crt
</VirtualHost>
Run Code Online (Sandbox Code Playgroud)

设置.py文件:

# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
# STATIC_URL = …
Run Code Online (Sandbox Code Playgroud)

python django static django-staticfiles google-cloud-storage

4
推荐指数
2
解决办法
5987
查看次数

Django 2.0 抛出 AttributeError: ''Image' 对象没有属性 'replace'"

在Django 2.0中尝试将html图像设置为我的静态路径+图像路径时,django开发服务器显示以下错误:

Error during template rendering

In template /Users/arikanevsky/webappgit/ari/templates/ari/software.html, error at line 5

'Image' object has no attribute 'replace'
Run Code Online (Sandbox Code Playgroud)

models.py 中的 Image 类:

class Image(models.Model):
    """This class contains a reference to the ImageField.

    It is part of a base of models comprising the webapp.

    """
    uplpath = '%Y/%m/%d'
    dfltpath = 'page_images/Y/M/D/no_img.jpg'

    image = models.ImageField(upload_to=uplpath, default=dfltpath)

    def __str__(self):
        """Return human readable string of self.image."""
        return self.image.name
Run Code Online (Sandbox Code Playgroud)

来自 urls.py 的 urlpatterns:

urlpatterns = [
    path('', views.index, name='index'),
    path('<int:page_id>/bio/', views.bio, name='bio'),
    path('<int:page_id>/software/', views.software, …
Run Code Online (Sandbox Code Playgroud)

django django-templates django-models django-views django-staticfiles

4
推荐指数
1
解决办法
4046
查看次数

django.core.exceptions.SuspiciousFileOperation:加入的路径位于基本路径组件之外

每次用于 django 网站时,这都很好用,但这次它给了我一个错误。

设置.py

STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'portfolio/static/')
]

STATIC_ROOT = os.path.join(BASE_DIR , 'static')
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Run Code Online (Sandbox Code Playgroud)

我的目录 Portfolio-Project/Portfolio/static/profile.jpg 中有一个 profile.jpg。它应该从这里收集静态并将静态文件粘贴到我的代码中提到的 Portfolio-project/static 中。但它给了我一些错误。

使用命令“Python manage.py collectstatic”后出错

django.core.exceptions.SuspiciousFileOperation: The joined path 
(C:\Users\Kiran\Desktop\portfolio-project\portfolio\static\Profile.jpg) is 
located outside of the base path component 
(C:\Users\Kiran\Desktop\portfolio- project\portfolio\static\)
Run Code Online (Sandbox Code Playgroud)

请帮忙。谢谢

python django python-2.7 python-3.x django-staticfiles

4
推荐指数
1
解决办法
7847
查看次数

尝试使用 devserver 提供静态文件时,Django 通道出错

我将我的项目移到另一个环境中,在安装依赖项并尝试运行 manage.py runserver - devserver 后,在请求静态文件时出现以下错误。坦率地说,我对这个错误完全迷失了,有人知道这是怎么回事吗?

    HTTP GET /static/admin/css/responsive.css 500 [0.21, 127.0.0.1:59982]
Exception inside application: async_to_sync can only be applied to async functions.
Traceback (most recent call last):
  File "/home/maxehleny/.local/share/virtualenvs/mysite-EdbyOLs2/lib/python3.6/site-packages/channels/staticfiles.py", line 41, in __call__
    dict(scope, static_base_url=self.base_url), receive, send
  File "/home/maxehleny/.local/share/virtualenvs/mysite-EdbyOLs2/lib/python3.6/site-packages/channels/staticfiles.py", line 56, in __call__
    return await super().__call__(scope, receive, send)
  File "/home/maxehleny/.local/share/virtualenvs/mysite-EdbyOLs2/lib/python3.6/site-packages/channels/http.py", line 198, in __call__
    await self.handle(scope, async_to_sync(send), body_stream)
  File "/home/maxehleny/.local/share/virtualenvs/mysite-EdbyOLs2/lib/python3.6/site-packages/asgiref/sync.py", line 105, in __init__
    raise TypeError("async_to_sync can only be applied to async functions.")
TypeError: async_to_sync can only be applied …
Run Code Online (Sandbox Code Playgroud)

django django-staticfiles django-channels

4
推荐指数
1
解决办法
316
查看次数

STATICFILES_DIRS 设置中的目录“/static/”不存在。(视觉工作室)

当我想要“python manage.py makemigrations”时,它返回以下内容。

\n
System check identified some issues:\n\nWARNINGS\n?: (staticfiles.W004) The directory '/static/' in the STATICFILES_DIRS setting does not exist.\n
Run Code Online (Sandbox Code Playgroud)\n

我应该如何解决这个问题?

\n
from pathlib import Path import os  BASE_DIR = Path(__file__).resolve().parent.parent  ALLOWED_HOSTS = ['*']  INSTALLED_APPS = [     'django.contrib.admin',     'django.contrib.auth',     'django.contrib.contenttypes',     'django.contrib.sessions',     'django.contrib.messages',     'django.contrib.staticfiles',      'products',     'orders', ]\n\nMIDDLEWARE = [     'django.middleware.security.SecurityMiddleware',     'django.contrib.sessions.middleware.SessionMiddleware',     'django.middleware.common.CommonMiddleware',     'django.middleware.csrf.CsrfViewMiddleware',     'django.contrib.auth.middleware.AuthenticationMiddleware',     'django.contrib.messages.middleware.MessageMiddleware',     'django.middleware.clickjacking.XFrameOptionsMiddleware', ]\n\nROOT_URLCONF = \xe2\x80\x98rtu_server.urls'  TEMPLATES = [     {         'BACKEND': 'django.template.backends.django.DjangoTemplates',         'DIRS': [],         'APP_DIRS': True,         'OPTIONS': {             'context_processors': [                 'django.template.context_processors.debug',                 'django.template.context_processors.request',                 'django.contrib.auth.context_processors.auth',                 'django.contrib.messages.context_processors.messages',             ],         },     }, …
Run Code Online (Sandbox Code Playgroud)

django django-staticfiles

4
推荐指数
1
解决办法
3万
查看次数

在设置中找不到“静态文件”的配置。STORAGES

运行 Django 4.2 时会出现此错误。默认值:django.contrib.staticfiles.storage.StaticFilesStorage已被弃用。

django static django-staticfiles python-django-storages

4
推荐指数
1
解决办法
2787
查看次数