하루일문
[django] image파일을 넣어보자 본문
개발자가 이미지를 넣는 경우
setting.py
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_URL = '/static/'
static 폴더를 만들고 이미지를 넣는다
sample.png
html
<img scr="{% static 'sample.png'%}" alt='sample'>
사용자가 업로드 + imagekit(resize, 화질 낮추기)
pip install pillow
pip install django-imagekit
setting.py
INSTALLED_APPS = [
'imagekit',
]
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.conf import settings
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill
profile_image_1= ProcessedImageField(blank = True, # == requir False
upload_to = 'image/1/',
# 크기를 자를것인가?
processors= [ResizeToFill(300, 300)],
format='JPEG',
# 화질
options={'quality' : 90},
)
-----------------
# upload_to 경로 조정
## 날짜별로
upload_to = '%Y/%m/%d'
## 유저별로
def profile(instance, filename):
return f'profiles/{instance.username}/{filename}'
image = ProcessedImageField(blank = True,
upload_to = profile,
# 크기를 맞출것인가?
processors= [ResizeToFit(30, 30)],
format='JPEG',
options={'quality' : 60},
)
models.py를 migrate해준다
python manage.py makemigrations
python manage.py migrate
pip freeze > requirements.txt
veiw.py
# request.FILES를 꼭 달아준다
form = ArticleForm(request.POST, request.FILES)
html에 이미지 등록
<form action="{% url 'articles:create' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form.ap_S}}
</form>
html 이미지가 있는 경우만 출력
# 맨위에 입력
{% load static %}
{% if balance.image_1 %}
<input type="image" src="{{ balance.image_1.url }}" class='card-border-1'>
<img src="{{balance.image_1.url}} " alt="img_1">
{% else %}
올린 이미지파일을 지울때 같이 media 삭제
models.py
def delete(self, *args, **kargs):
if self.profile_image:
os.remove(os.path.join(settings.MEDIA_ROOT, self.profile_image.path))
super(User, self).delete(*args, **kargs)
def save(self, *args, **kwargs):
if self.id:
old_user = User.objects.get(id=self.id)
if self.profile_image != old_user.profile_image:
if old_user.profile_image:
os.remove(os.path.join(settings.MEDIA_ROOT, old_user.profile_image.path))
super(User, self).save(*args, **kwargs)
'django' 카테고리의 다른 글
[Django] multi image 넣기 (0) | 2023.05.02 |
---|---|
[django] 소셜로그인(카카오) (0) | 2023.05.02 |
[Django] 여러 감정 표현하기 (0) | 2023.05.01 |
[django] 검색을 해보자 (0) | 2023.04.27 |
[django] 게시글, 댓글이 언제 쓰였을지 표시하기 (0) | 2023.04.26 |