본문 바로가기
Django11

Django Flash Messages

by 자동매매 2023. 4. 29.

Introduction to the Django Flash Messages

플래시 메시지는 일회성 알림 메시지입니다. Django에서 플래시 메시지를 표시하려면 django.contrib 모듈의 messages 사용합니다.

 

from django.contrib import messages

 

The messages have some useful functions for displaying information, warning, and error messages:

  • messages.debug – displays a debug message.
  • messages.info – displays an informational message.
  • messages.success – displays a success message.
  • messages.warning – displays a warning message.
  • messages.error – displays an error message.

All of these functions accept an HttpRequest object as the first argument and a message as the second argument.

 

Django Flash message example

We’ll implement flash messages for the blog app in the django_project.

Creating Django flash messages

Modify the create_post() function by adding the flash messages:

from django.shortcuts import render,redirect
from django.contrib import messages
from .models import Post
from .forms import PostForm


def create_post(request):
    if request.method == 'GET':
        context = {'form': PostForm()}
        return render(request,'blog/post_form.html',context)
    elif request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'The post has been created successfully.')
            return redirect('posts')
        else:
            messages.error(request, 'Please correct the following errors:')
            return render(request,'blog/post_form.html',{'form':form})

 

Django 플래시 메시지 예제

django_project에서 블로그 앱에  대한 플래시 메시지를 구현합니다.

Django 플래시 메시지 만들기

 플래시 메시지를 추가하여 create_post() 함수를 수정합니다.

from django.shortcuts import render,redirect
from django.contrib import messages
from .models import Post
from .forms import PostForm
 
 
def create_post(request):
    if request.method == 'GET':
        context = {'form': PostForm()}
        return render(request,'blog/post_form.html',context)
    elif request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'The post has been created successfully.')
            return redirect('posts')
        else:
            messages.error(request, 'Please correct the following errors:')
            return render(request,'blog/post_form.html',{'form':form})

 

How it works.

First, import messages from the django.contrib:

from django.contrib import messages

 

Second, create a success message after saving the form values into the database by calling the success() function:

messages.success(request, 'The post has been created successfully.')

 

Third, create an error message if the form is not valid by calling the error() function:

messages.error(request, 'Please correct the following errors:')

 

Displaying flash messages

Modify the base.html template to display flash messages:

 

 

작동 방식.

먼저 django.contrib에서 메시지를 가져옵니다.

 django.contrib 가져 오기 메시지에서

 

둘째, success() 함수를 호출하여 양식 값을 데이터베이스에 저장한 성공 메시지를 만듭니다.

messages.success(request, '게시물이 성공적으로 생성되었습니다.' )

 

셋째, 양식이 유효하지 않은 경우 error() 함수를 호출하여 오류 메시지를 만듭니다.

messages.error(요청, ' 다음 오류를 수정하십시오:')

 

플래시 메시지 표시하기

기본 .html 템플릿을 수정하여 플래시 메시지를 표시합니다.

{%load static %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="{% static 'css/style.css' %}" />
    <script src="{% static 'js/app.js' %}" defer></script>
    <title>My Site</title>
  </head>
  <body>
      {% if messages %}
           <div class="messages">
           {% for message in messages %}
                 <div class="alert {% if message.tags %}alert-{{ message.tags }}"{% endif %}>
                       {{ message }}
                 </div>
           {% endfor %}
           </div>
      {% endif %}
         
    {%block content%}
    {%endblock content%}
  </body>
</html>

Code language: HTML, XML (xml)

If you navigate to the form http://127.0.0.1/post/create, enter the values, and click the Save button:

 

… you’ll see a success message:

 

If you refresh the page, the message will disappear because it displays only once.

When you skip entering a value for the title field and click the Save button:

 

… you’ll see an error message:

 

Summary

·   Use the messages from django.contrib to create and display messages.

·   django.contrib  메시지를  사용하여 메시지를 만들고 표시합니다.

'Django11' 카테고리의 다른 글

Django Form 종류  (0) 2023.05.01
Django Migrations  (0) 2023.04.28
Django Models  (0) 2023.04.28
Django 배포  (0) 2023.04.14
Getting Started with Django  (0) 2023.04.08

댓글