Static files管理
static files指一些用到的像css,javascript,images之类的文件。
在开发阶段:
1.在settings设置INSTALLED_APPS中添加'django.contrib.staticfiles'。
2.将STATIC_URL设置为'/static/'。
3.将某个app要用的静态文件放置到my_app/static/my_app中,例如my_app/static/my_app/my_image.jpg.
当然也可以直接放在my_app/static中,但这样的话,如果在不同的app中有相同名字的静态文件,就会产生冲突。
4.模板中使用
- {% load static %}
- <img src="{% static 'my_app/myexample.jpg' %}" alt="My image"/>
5.如果有些不是某个app特用的静态文件,可以建立static文件夹将静态文件放置其中,settings设置:
- STATICFILES_DIRS = (
- os.path.join(BASE_DIR, "static"),
- '/var/www/static/',
- )
这样,在开发环境中,settings.DEBUG设置为True时,运行runserver就可以访问静态文件了。
如果INSTALLED_APPS中没有包含'django.contrib.staticfiles',需要手动运行django.contrib.staticfiles.views.serve()。
- from django.conf import settings
- from django.contrib.staticfiles import views
-
- if settings.DEBUG:
- urlpatterns += [
- url(r'^static/(?P<path>.*)$', views.serve),
- ]
或者
- from django.conf import settings
- from django.conf.urls.static import static
- urlpatterns = [
- # ... the rest of your URLconf goes here ...
- ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
以上都在DEBUG设置为True时起作用。
在生产环境中,就需要使用反向代理服务器直接访问静态文件,需要将静态文件转移到代理服务器可以访问的文件夹,设置
- STATIC_ROOT = "/var/www/example.com/static/"
然后运行
- python manage.py collectstatic
将各个app内的静态文件及STATICFILES_DIRS内的静态文件收集起来放置到STATIC_ROOT中由服务器apache或nhinx管理即可。
Media管理
MEDIA:指用户上传的文件,比如在Model里面的FileFIeld,ImageField上传的文件。
假如有个Model
- from django.db import models
- class Car(models.Model):
- name = models.CharField(max_length=255)
- price = models.DecimalField(max_digits=5, decimal_places=2)
- photo = models.ImageField(upload_to='cars')
设置MEDIA_ROOT=os.path.join(BASE_DIR , 'media'),用来存储用户上传的文件
MEDIA_URL=/media/,为MEDIA_ROOT中的文件建立url地址。
当建立一个Car实例时,Car的ImageField字段图片就存到media/cars文件夹里面
- >>> car = Car.objects.get(name="57 Chevy")
- >>> car.photo
- <ImageFieldFile: chevy.jpg>
- >>> car.photo.name
- u'cars/chevy.jpg'
- >>> car.photo.path
- u'/media/cars/chevy.jpg'
- >>> car.photo.url
- u'/media/cars/chevy.jpg'
在模板中使用图片
- <img src="{{ car.photo.url }}" alt="My image"/>
在urls.py中使用 django.contrib.staticfiles.views.serve() view
- from django.conf import settings #from myapp import settings
- from django.conf.urls.static import static
-
- urlpatterns = patterns('',
- # ... the rest of your URLconf goes here ...
- ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
这样就可以使用media文件了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。