I've got a simple Django template that allows a user to input an image from the system. It should accept only JPEG, JPG, PNG and SVG files. The first three seems to work well. However, SVG doesnt get uploaded. Instead, it sends an error message stating: 'Upload a valid image. The file you uploaded was either not an image or a corrupted image'
How do I store a SVG file into my database model?
You can view my current code below:
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.ImageField(upload_to = get_directory_path, default = 'media/sample.png')
created_date = models.DateTimeField(auto_now = True)
def __str__(self):
return str(self.id)
forms.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>