Day 20 Django for KN

김의석 ·2024년 2월 26일

Django

목록 보기
20/39
post-thumbnail

Django for KN(Koinonia)

  • 해당 문서는 사귐의 교회 청소년부 출석부 프로젝트를 위한 Django 학습 내용과 개발 과정을 기록함

메세지 프레임워크

# views.py 작성

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">
<!-- Bootstrap의 CSS 파일을 Content Delivery Network (CDN)을 통해 불러오고 있습니다. -->


 <div class="container"> 
</div>
<!-- 웹 페이지의 내용을 감싸는 역할을 하며, 주로 컨텐츠를 가운데 정렬하고 적절한 여백을 제공 -->

<!--
class는 주로 HTML과 CSS, JavaScript 간의 연결고리로 사용되며, 
스타일과 동작을 효과적으로 관리한다. 아래의 예시
-->

<!-- class= container와 CSS/JS 사용 예시 -->

<stlye>
.container {
    width: 80%;
    margin: 0 auto; /* 가운데 정렬을 위한 마진 설정 */
    padding: 20px;
    /* 기타 스타일 규칙들 */
}
</stlye>

<!-- JavaScript 예시: container 클래스를 가진 요소를 선택하고 조작하기 -->
<script>
var containerElement = document.querySelector('.container');
containerElement.style.backgroundColor = 'lightgray';
</script>



<!-- message 기본 설정-->
{% 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 탬플릿 태그

#  django-bootstrap5 install 

# setting.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
	'django-bootstrap5',
    # 순서 중요. 순서가 다를 경우 '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 사용)
<!-- 소스코드 _messages_as_toast.html 경로 저장 후-->

<div class="container">
    <h1>core</h1>
    {% include "_messages_as_toast.html" %}
</div>
  • "_messages_as_toast.html" : 이 html은 view에 의해서 직접적으로 사용되는 것이 아니라 템플릿이 의해서 사용되어지는(include)템플릿이기 때문에 "_"를 붙여 저장함
  • 경로 이슈 : 간접사용 템플릿은 app 내 templates 바로 아래에 저장되어야함
JS로 토스트 스타일 메시지 노출

<!-- head에 코드 추가 -->

 <!-- CSS / JavaScript 링크 -->
    <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 스타일 따라하기

<!-- 코드 추가-->
    <!-- CSS 조작  -->
    <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로 토스트 스타일 메시지 노출-메세지 목록 데이터와 자바 스크립트 코드를 분리하기

# core/context_processors.py 경로에 추가

# settings.py 
# core.context_processors.messages_list 추가
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가 넘을 경우 세션 저장소를 사용합니다.
profile
널리 이롭게

0개의 댓글