Djang中静态文件配置方法
下面通过图文并茂的方法给大家详细介绍下Djang中静态文件配置方法
一、django静态文件配置原理
静态文件配置就是为了让用户请求时django服务器能找到静态文件返回。
首先要理解几个概念:
代码如下:
SITE_ROOT = os.path.dirname(os.path.abspath(__file__))
SITE_ROOT = os.path.abspath(os.path.join(SITE_ROOT, '../'))
STATIC_ROOT = os.path.join(SITE_ROOT, 'collectedstatic')
STATIC_URL配置项
django模板中,可以引用{{STATIC_URL}}变量避免把路径写死。通常使用默认设置
代码如下:
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX配置项
ADMIN_MEDIA_PREFIX必须为如下配置,以便staticfiles能够正确找到django.contrib.admin的静态资源:
代码如下:
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
在模板中使用STATIC_URL
代码如下:
原理懂了后,接下来介绍开发环境和生产环境中静态文件具体配置。
我的django版本是1.4.21,以此版本做介绍。
代码如下:
>>> import django
>>> print django.get_version()
1.4.21
二、开发环境
django1.4,21中默认已安装了staticfiles app,所以开发环境中对静态文件的访问不需要对django做任何配置。
有一点:开发环境staticfiles查找静态文件的顺序取决于STATIC_FINDERS配置项,默认配置
代码如下:
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
FileStstemFinder用来用STATICFILES_DIRS【默认为空】指定的路径中查找额外的静态文件。像jquery,bootstrap等这样公用的资源文件都是在多个不同的app中共用的,django提供了公有的目录来放这些文件,这个配置参数就是:STATICFILES_DIRS
AppDirectoriesFinder从INSTALLED_APPS元组中的APP所在包的static目录中查找资源文件。
使用如下。
1、新建项目lxyproject
代码如下:
[root@yl-web srv]# django-admin.py startproject lxyproject
2、在项目中新建一个app名叫hello
代码如下:
[root@yl-web lxyproject]# python manage.py startapp hello
[root@yl-web lxyproject]# ls
hello lxyproject manage.py
在hello app下建一个static目录用来存放静态文件。
代码如下:
[root@yl-web hello]# mkdir static
[root@yl-web hello]# ls
__init__.py models.py static tests.py views.py
然后在static目录新建一个hello.txt的静态文件。
代码如下:
[root@yl-web hello]# cd static/
[root@yl-web static]# ls
hello.txt
[root@yl-web static]# cat hello.txt
hello.txt's content:congratulations!!
3、在项目的settings.py文件中INSTALLED_APPS中配置hello app
代码如下:
INSTALLED_APPS = (
...
'hello',
)
4、运行项目
代码如下:
[root@yl-web lxyproject]# python manage.py runserver 0.0.0.0:9000
5、通过url访问
在static目录下新建一个images目录放一张sheep.png图片,同理通过url访问
三、生产环境
前面也说了,在生成环境中,集中存放静态资源有利于使用Lighttpd/Nginx托管静态资源。而生产环境一般是把静态文件放在项目根目录下的static目录下。
默认配置
代码如下:
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
)
我们要做的是
1、配置服务器,我用的是apache。
安装配置详情可参考:
代码如下:
[root@yl-web lxyproject]# python manage.py collectstatic
You have requested to collect static files at the destination
location as specified in your settings.
This will overwrite existing files!
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: yes
Copying '/srv/lxyproject/hello/static/images/sheep.png'
1 static file copied.
5、配置服务器,将/static/路径指向STATIC_ROOT目录。
即在虚拟主机中配置
代码如下:
Alias /static/ /srv/lxyproject/collectedstatic/
6、配置至此完成,通过浏览器访问
真正发布一个django项目时,对静态文件的管理可能需要额外做一些工作:
Less / CoffeeScript 等自动编译成css/js
"压缩" css/js文件,提高浏览器加载速度
合并零碎的css/js文件,减少浏览器请求次数
静态资源文件的版本话:浏览器会缓存静态文件,后台代码和静态资源文件都发生更新后,浏览器很可能从缓存提取过期的静态资源,导致页面显示异常。
以上就是Djang中静态文件配置方法的全部内容,希望大家喜欢。

Outils d'IA chauds

Undresser.AI Undress
Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover
Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool
Images de déshabillage gratuites

Clothoff.io
Dissolvant de vêtements AI

Video Face Swap
Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Article chaud

Outils chauds

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Solution aux problèmes d'autorisation Lors de la visualisation de la version Python dans Linux Terminal Lorsque vous essayez d'afficher la version Python dans Linux Terminal, entrez Python ...

Lorsque vous utilisez la bibliothèque Pandas de Python, comment copier des colonnes entières entre deux frames de données avec différentes structures est un problème courant. Supposons que nous ayons deux dats ...

Comment enseigner les bases de la programmation novice en informatique dans les 10 heures? Si vous n'avez que 10 heures pour enseigner à l'informatique novice des connaissances en programmation, que choisissez-vous d'enseigner ...

Comment éviter d'être détecté lors de l'utilisation de FiddlereVerywhere pour les lectures d'homme dans le milieu lorsque vous utilisez FiddlereVerywhere ...

Comment Uvicorn écoute-t-il en permanence les demandes HTTP? Uvicorn est un serveur Web léger basé sur ASGI. L'une de ses fonctions principales est d'écouter les demandes HTTP et de procéder ...

L'article traite des bibliothèques Python populaires comme Numpy, Pandas, Matplotlib, Scikit-Learn, Tensorflow, Django, Flask et Demandes, détaillant leurs utilisations dans le calcul scientifique, l'analyse des données, la visualisation, l'apprentissage automatique, le développement Web et H et H

Dans Python, comment créer dynamiquement un objet via une chaîne et appeler ses méthodes? Il s'agit d'une exigence de programmation courante, surtout si elle doit être configurée ou exécutée ...

Utilisation de Python dans Linux Terminal ...
