search
HomeBackend DevelopmentPython TutorialDjang中静态文件配置方法

下面通过图文并茂的方法给大家详细介绍下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中静态文件配置方法的全部内容,希望大家喜欢。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)