Static files management
Static files refer to files such as css, javascript, and images.
In the development phase:
1. Add 'django. contrib. staticfiles' in settings to set INSTALLED_APPS '.
2. Set STATIC_URL to '/static /'.
3. Place the static files used by an app to my_app/static/my_app, for example, my_app/static/my_ap.my_image.jpg.
Of course, it can also be directly stored in my_app/static, but in this case, if there are static files with the same name in different apps, there will be conflicts.
4. Use in the template
{% load staticfiles %}
5. If some static files are not used by an app, you can create a static folder to place the static files, and set settings:
STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), '/var/www/static/',)
In the deployment phase, Set
STATIC_ROOT = "/var/www/example.com/static/"
Then run
python manage.py collectstatic
Collect static files in each app and static files in STATICFILES_DIRS and place them in STATIC_ROOT.
Media Management
MEDIA: a user-uploaded file, such as a FileFIeld in the Model and an ImageField file.
Assume there is a Model.
from django.db import modelsclass Car(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=5, decimal_places=2) photo = models.ImageField(upload_to='cars')
Set MEDIA_ROOT = OS. path. join (BASE_DIR, 'media') to store uploaded files.
MEDIA_URL =/media/, which creates a url for the file in MEDIA_ROOT.
When a Car instance is created, the image of the Car ImageField is saved in the media/cars folder.
>>> car = Car.objects.get(name="57 Chevy")>>> car.photo<ImageFieldFile: chevy.jpg>>>> car.photo.nameu'cars/chevy.jpg'>>> car.photo.pathu'/media/cars/chevy.jpg'>>> car.photo.urlu'/media/cars/chevy.jpg'
Use images in templates
Use in urls. pyDjango. contrib. staticfiles. views. serve ()View
from django.conf import settings #from myapp import settingsfrom django.conf.urls.static import staticurlpatterns = patterns('', # ... the rest of your URLconf goes here ...) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In this way, you can use the media file.