settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS= [str(BASE_DIR.joinpath('static'))]
STATIC_ROOT = BASE_DIR.joinpath('staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = str(BASE_DIR.joinpath('media'))
config/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('proj.urls')),
] += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
class Book(models.Model):
image = models.ImageField(upload_to='upload/', blank=True, default=None, null=True)
views.py
class BookCreateView(CreateView):
model = Book
template_name = "book_new.html"
fields = "__all__"
book_new.html
{% extends 'base.html' %}
{% block content %}
<h1>New Book</h1>
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
{% endblock content %}
proj/urls.py
urlpatterns = [
path("", home_view, name="home"),
path("book/new/", BookCreateView.as_view(), name="book_new"),
]
I have written this code which will upload the image to /media/upload/
and the path of the file will be saved on the database like upload/image_file.png
. I don't want to store the file path in the database, I want to read the file, convert it to base64 and store the encoded string in the database. How can I do that? I've searched a lot and tried to figure this out on my own as I usually do, but this one's a little hard for me, here's what I've read so far:
- Binary image display in Django template
- Save base64 image in django file field
- Saving a decoded temporary image to Django Imagefield
- a StringIO like class, that extends django.core.files.File
- Django: using base64 to store images in the DB
- Encode Base64 Django ImageField Stream
- https://medium.com/@omaraamir19966/image-handling-with-django-de4f85a0e907
- https://idiomaticprogrammers.com/post/how-to-save-base64-encoded-image-to-django-imagefield/
- https://stackabuse.com/encoding-and-decoding-base64-strings-in-python/