The Seven Year Itch.

MENU

Django The messages framework

December 26, 2017 • Read: 311 • Python,Django

Django消息闪现官方文档

个人觉得和FLask中的Flash无区别!

  • 后端
from django.contrib import messages

def home_create(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        messages.success(request,"successfully created")
    context = {
        "form": form,
    }
    return render(request, "post_create.html", context)
  • 前端

官方示例:

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

自己要给加样式的话,可以配合Bootstrap的样式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create</title>
</head>
<body>
<h1>Create</h1>
{% if messages %}
    <ul class="messages">
        {% for message in messages %}
            <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
        {% endfor %}
    </ul>
{% endif %}
<form method="post" action="">
    {{ form.as_p }}
    <input type="submit">
    {% csrf_token %}
</form>
</body>
</html>
Tags: None
Archives QR Code
QR Code for this page
Tipping QR Code