Django for KN(Koinonia)
- 해당 문서는 사귐의 교회 청소년부 출석부 프로젝트를 위한 Django 학습 내용과 개발 과정을 기록함
메세지 프레임워크
from django.contrib import messages
def index(request):
messages.debug(request, message='디버그 메세지')
messages.info(request, message='정보 메세지')
messages.success(request, message='성공 메세지')
messages.warning(request, message='경고 메세지')
messages.error(request, message='에러메시지')
return render(request, 'core/index.html')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css">
<div class="container">
</div>
<stlye>
.container {
width: 80%;
margin: 0 auto; /* 가운데 정렬을 위한 마진 설정 */
padding: 20px;
/* 기타 스타일 규칙들 */
}
</stlye>
<script>
var containerElement = document.querySelector('.container');
containerElement.style.backgroundColor = 'lightgray';
</script>
{% for message in messages %}
<div class="alert
{% if message.level_tag == "debug" %}
alert-secondary
{% elif message.level_tag == "error" %}
alert-danger
{% else %}
alert-{{ message.level_tag }}
{% endif %}">
{{ message.message }}
</div>
bootstrap_massages 탬플릿 태그
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django-bootstrap5',
'core',
]
{% load django-bootstrap5 %}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
{% bootstrap_css %}
{% bootstrap_javascript %}
</head>
<body>
<div class="container">
<h1>core</h1>
{% bootstrap_messages %}
</div>
</body>
- bootstrap_massages 탬플릿 태그를 통해 메세지를 간단히 출력.
토스트 스타일 메시지 노출(bootstrap5 사용)
<div class="container">
<h1>core</h1>
{% include "_messages_as_toast.html" %}
</div>
- "_messages_as_toast.html" : 이 html은 view에 의해서 직접적으로 사용되는 것이 아니라 템플릿이 의해서 사용되어지는(include)템플릿이기 때문에 "_"를 붙여 저장함
- 경로 이슈 : 간접사용 템플릿은 app 내 templates 바로 아래에 저장되어야함
JS로 토스트 스타일 메시지 노출
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css" />
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
{% if messages %}
<script>
{% for message in messages %}
Toastify({
text: "{{ message }}",
duration: 3000,
}).showToast();
{% endfor %}
</script>
{% endif %}
JS로 토스트 스타일 메시지 노출-bootstrap5 스타일 따라하기
<style>
.alert-secondary, .alert-debug { color: #41464b; background: #e2e3e5; border: 1px solid #d3d6d8; }
.alert-info { color: #055160; background: #cff4fc; border: 1px solid #b6effb; }
.alert-success { color: #0f5132; background: #d1e7dd; border: 1px solid #badbcc; }
.alert-warning { color: #664d03; background: #fff3cd; border: 1px solid #ffecb5; }
.alert-danger, .alert-error { color: #842029; background: #f8d7da; border: 1px solid #f5c2c7; }
</style>
{% if messages %}
<script>
{% for message in messages %}
Toastify({
text: "{{ message }}",
duration: 3000,
className: "alert-{{ message.level_tag }}", <!--추가 -->
}).showToast();
{% endfor %}
</script>
{% endif %}
JS로 토스트 스타일 메시지 노출-메세지 목록 데이터와 자바 스크립트 코드를 분리하기
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': ['core.context_processors.messages_list',
],
},
},
]
<div class="container">
<h1>core</h1>
{{ messages_list|json_script:"messages-list"}}
</div>
<script>
const jsonString = document.querySelector("#messages-list").textContent;
const messagesList = JSON.parse(jsonString);
console.log(messagesList);
messagesList.forEach(({ level_tag, message }) => {
Toastify({
text: message,
className: `alert-${level_tag}`,
duration: 3000,
}).showToast();
});
</script>
메시지 스토리지
- SessionStorage
- CookieStorage
- 모든 메세지를 쿠기에 저장하며, 조작 방지를 위해 비밀 해시로 해명 됨
- 2KB가 넘는 경유 오래된 메시지가 제거
- FallbackStorage(디폴트 값)
- 쿠키 저장소를 먼저 사용하고, 저장된 메시지가 2kb가 넘을 경우 세션 저장소를 사용합니다.