👉 장고 공식문서 _ managing files
=> 이미지 파일 관리를 위해서 Pillow pip를 설치해야한다.
When you use a FileField
or ImageField
, Django provides a set of APIs you can use to deal with that file. Consider the following model, using an ImageField
to store a photo:
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')
specs = models.FileField(upload_to='specs')
class ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)
upload_to
: 이미지를 저장 할 경로설정
height_field
: 높이 지정
width_field
: 폭 지정
max_length
: DB에서 문자열처럼 취급하기 때문에 최대 길이 지정 가능
blank=True
: 빈 이미지 허용
pip install Pillow
from django.db import models
class Article(models.Model):
...
image = models.ImageField(upload_to='images/', blank=True)
$ python manage.py makemigrations
$ python manage.py makemigrations
👉 enctype MDN문서
application/x-www-form-urlencoded
: The initial default type.
multipart/form-data
: The type that allows file <input> element(s) to upload file data.
text/plain
: Ambiguous format, human readable content not reliably interpretable by computer.
form 태그에 enctype 추가하기
{% extends 'base.html' %}
{% block body %}
<h1>create 페이지</h1>
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ article_form.as_p }}
<input type="submit" value="제출하기">
</form>
{% endblock body %}
request.FILES 추가하기
def create(request):
if request.method == 'POST':
article_form = ArticleForm(request.POST, request.FILES)
if article_form.is_valid():
...
DEFAULT값으로 둘 다 ' ' 공백이다. 따라서 경로를 지정해주어야 url을 활용할 수 있다.
...
# Media files (user uploaded filed)
MEDIA_ROOT = BASE_DIR / 'images'
MEDIA_URL = '/media/'
...
👉 urls.py에 추가 설정 해주기 django 공식문서
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
다음과 같이
ImageSpecField
또는ProcessedImageField
를 통해 이미지 리사이징 가능하다
# 출처 : django-imagekit-github
from django.db import models
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
class Profile(models.Model):
avatar = models.ImageField(upload_to='avatars')
avatar_thumbnail = ImageSpecField(source='avatar',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
# 출처 : django-imagekit-github
from django.db import models
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill
class Profile(models.Model):
avatar_thumbnail = ProcessedImageField(upload_to='avatars',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
$ pip install django-imagekit
INSTALLED_APPS = [
'imagekit',
...
원본 유지하면서 리사이징 해보기
from django.db import models
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
class Article(models.Model):
...
image = models.ImageField(upload_to='images/', blank=True)
image_thumbnail = ImageSpecField(source='image',
processors=[ResizeToFill(100,100)],format='JPEG', options={'quality': 60})
...
<img src="{{ article.image_thumbnail.url }}" alt="{{ article.image }}">
...
이대로 진행하면 에러난다. 왜? 이미지가 없는데 url을 가져오라고 하면 에러. 분기처리 필요
...
{% if article.image %}
<img src="{{ article.image_thumbnail.url }}" alt="{{ article.image }}">
{% endif %}
...
request.FILES
폼에 추가해주기
...
def update(request, pk):
article = Article.objects.get(pk=pk)
if request.method == 'POST':
article_form = ArticleForm(request.POST, request.FILES, instance=article)
...