Django(22) Making Flash Message In Django

To make your actions more user-friendly, you can use flash message. Here are some tips.

Making Flash Message In Django

  1. In "views.py", you should from django.contrib import messages. And change the code of addUser to this.
def addUser(request):
    form = RegistrationForm(request.POST)

    if form.is_valid():
        my_register = RegistrationData(username=form.cleaned_data['username'],
                                       password=form.cleaned_data['password'],
                                       email=form.cleaned_data['email'],
                                       phone=form.cleaned_data['phone'])

        my_register.save()
        # new added
        messages.add_message(request, messages.SUCCESS, 'You have signup successfully!')

    return redirect('register')
  1. And in "signup.html" file, you can add these codes to your own.
{% extends 'base.html' %}

{% block title %} Sign Up {% endblock %}

{% block body %}

<div class="container">
    <h1>Signup Form</h1>
<!--- adding code -->
    <ul class="messages">

        {% for msg in messages %}

        <li>

            <div class="alert alert-{{msg.level_tag}}" role="alert">

                {{ msg.message }}

            </div>

        </li>

        {% endfor %}

    </ul>
<!-- end adding code -->
    <form action="{% url 'addUser' %}" method="post">

        {% csrf_token %}

        <form>
            <div class="form-group">
                <label>Username</label>

                {{ form.username }}

            </div>
            <div class="form-group">
                <label>Password</label>

                {{ form.password }}

            </div>
            <div class="form-group">
                <label>Email address</label>
                <!-- <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> -->

                {{ form.email }}

                <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone
                    else.</small>
            </div>
            <div class="form-group">
                <label>Phone</label>
                <!-- <input type="password" class="form-control" id="exampleInputPassword1"> -->

                {{ form.phone }}

            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>

    </form>

</div>

{% endblock %}
  1. After input information in sign up page, you should see this.


    Django(22)_Making_Flash_Message_In_Django_1.png
  2. Also, database and admin panel will change correspondingly.

So far, you have learnt how to use flash message in Django. Hopefully, it helps.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容