在表单中上传图片后如何显示django消息?

时间:2019-08-06 08:44:41

标签: django

我创建了一个简单的django html页面,该页面使用户可以上传图像。如果图像格式为PNG,JPG,JPEG或SVG,则应显示一条消息“图像成功上传”,并将文件保存在目录中。但是,如果除此之外还有其他格式,则应显示一条消息:“不成功,请以PNG,JPG,SVG或JPEG格式上传”。如何显示消息?我尝试使用SuccessMessageMixin,但它同时显示成功和失败上传的消息。请帮忙。

您可以在下面查看我当前的代码:

models.py:

from django.db import models
import os
from PIL import Image
from datetime import date
import datetime


def get_directory_path(instance, filename):
    file_extension = os.path.splitext(filename)
    today = date.today()
    t = datetime.datetime.now() 
    day, month, year = today.day, today.month, today.year
    hour, minutes, seconds = t.hour, t.minute, t.second
    if file_extension[1] in ['.jpg','.png','.jpeg','.svg']:
        filename = str(day) + str(month) + str(year) + str(hour) + str(minutes) + str(seconds) + '.png'
        dir = 'media'
    else:
        dir = 'others'
    path = '{0}/{1}'.format(dir, filename)
    return path

# Create your models here.
class Image(models.Model):
    image = models.FileField(upload_to = get_directory_path, default = 'media/sample.png')
    created_date = models.DateTimeField(auto_now = True)

    def __str__(self):
        return str(self.id)

views.py:

from django.shortcuts import render
from django.db import models
from django.views.generic import TemplateView, CreateView
from myapp.forms import ImageForm
from django.urls import reverse_lazy
from django.contrib.messages.views import SuccessMessageMixin

class BaseView(TemplateView):
    template_name = "result.html"

class ImageView(SuccessMessageMixin, CreateView):
    template_name = "insert_image.html"
    form_class = ImageForm
    success_message = "Uploaded image sucessfully"
    success_url = reverse_lazy("base")

forms.py

from django import forms

from myapp.models import Image

class ImageForm(forms.ModelForm):
    class Meta:
        model = Image
        exclude = ('created_date',)

insert_image.html

{% load staticfiles %}
<body>

    <h1> Please upload an image below </h1>

    <form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {{form.as_p}}
        <button type="submit"> Submit </button>
    </form>

    <p> Required format: PNG, JPEG, JPG, SVG </p>
</body>

result.html

<body>

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

<button> <a href = '{% url "insert_image" %}' style="text-decoration: none;"> Return </button> </a>

</body>

0 个答案:

没有答案