首页 > 解决方案 > 如何在 Django 模型中存储 SVG 文件?

问题描述

我有一个简单的 Django 模板,允许用户从系统输入图像。它应该只接受 JPEG、JPG、PNG 和 SVG 文件。前三个似乎运作良好。但是,SVG 不会被上传。相反,它会发送一条错误消息,说明:“上传有效图像。您上传的文件不是图像或损坏的图像'

如何将 SVG 文件存储到我的数据库模型中?

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

模型.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.ImageField(upload_to = get_directory_path, default = 'media/sample.png')
    created_date = models.DateTimeField(auto_now = True)

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

表格.py:

from django import forms

from myapp.models import Image

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

insert_image.html

{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
    <title> Insert an image </title>
</head>
<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>
</html>

标签: djangosvg

解决方案


推荐阅读