django | 13. static
정적파일
프로젝트 안에 있으면서 계속 재사용할 수 잇는 css, js, image 파일
static 디렉토리 위치 추가하기
# settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'djangoMaster', 'static')
]
# settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'djangoMaster', 'static')
]
프로젝트 폴더인 djangoMaster의 static폴더에서 static 파일을 관리할거라는 의미이다.
static 디렉토리 만들고 스타일시트 작성하기
/* djangoMaster>static>css>style.css */
h1 {
color: orange;
}
템플릿에 스타일 적용하기
/* djangoMaster>static>css>style.css */
h1 {
color: orange;
}
적용하고 싶은 HTML 템플릿에 코드를 작성해준다.
<!-- djangoMaster>templates>question_list.html -->
{% extends 'base.html' %}
{% block content %}
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
...
base.html에 스타일 적용하기
<!-- djangoMaster>templates>base.html -->
{% load static %} <!-- 가장 위에 static 추가 -->
<!doctype html>
...
<link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- static 추가 -->
...
</html>
<!-- djangoMaster>templates>base.html -->
{% load static %} <!-- 가장 위에 static 추가 -->
<!doctype html>
...
<link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- static 추가 -->
...
</html>
base.html에 static을 상속하였기 때문에 바로 위에서 작성했던 question_list.html에 상속한 static은 삭제하여도 된다.
<!-- djangoMaster>templates>question_list.html -->
{% extends 'base.html' %}
{% block content %}
{% load static %} <!-- 삭제 -->
<link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- 삭제 -->
...
이미지 추가하기
staic 디렉토리 밑에 images 디렉토리를 만들고 원하는 사진을 업로드해준다.
넣고싶은 곳에
<!-- djangoMaster>templates>main.html -->
<img src="{% static 'images/[이미지파일이름].png' %}" alt="[사진이 안 뜰 경우 대신 보여줄 멘트]">
main.html에 사진을 등록해보겠다.
<!-- djangoMaster>templates>main.html -->
{% extends 'base.html' %}
{% block content %}
...
<img src="{% static 'images/django.png' %}" alt="안보이지만 사자야">
{% endblock %}
경로를 확실히 해준다.
템플릿 태그 사용 시 {% %}(O) { % % }(X)
사진이 너무 커 CSS로 크기를 조절하였다.
/* style.css */
...
img {
width: 30%;
height: auto;
}
Author And Source
이 문제에 관하여(django | 13. static), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@printver_2world/django-13.-static저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)