django - 如何在 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>
解决方案
推荐阅读
- blogger - 如何在移动设备上隐藏 Blogger 的侧边栏
- javascript - 检查字符串中的字符是否唯一
- jquery - 如何在 jquery 中创建滑块
- ajax - 如何在 PHP 和 Ajax 中使用两个下拉列表获取自动响应值?
- opencv - 哪种使用 OpenCV 的对象检测方法最适合不断变化的环境?
- angular - Angular API 调用的 HTTP-GET 请求不起作用
- php - 如何从数据库中自动选择保存值以选择 HTML 标记
- c - 为什么正确打印此非空终止字符串
- python - 有谁知道如何从 csv 获取信息?
- appium - 取消点击真实设备(移动设备)上的按钮