Last active
March 7, 2024 05:40
-
-
Save AshishPandagre/c6a3b0f5ff4724ed5d29b4ff347828f4 to your computer and use it in GitHub Desktop.
Add tinymce editor in django (along with drag and drop image upload)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib import admin | |
from .models import Post | |
@admin.register(Post) | |
class PostAdmin(admin.ModelAdmin): | |
class Media: | |
js = ('tinyInject.js',) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
# I have created a test model. | |
class Post(models.Model): | |
title = models.CharField(max_length=20) | |
content = models.TextField() # tinymce will be applied here | |
def ___str__(self): | |
return self.title |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/urls.py | |
# Add this path to your app/urls.py | |
urlpatterns = [ | |
path('upload_image/', views.upload_image), | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from django.conf import settings | |
from django.http import JsonResponse | |
from django.views.decorators.csrf import csrf_exempt | |
@csrf_exempt | |
def upload_image(request): | |
if request.method == "POST": | |
file_obj = request.FILES['file'] | |
file_name_suffix = file_obj.name.split(".")[-1] | |
if file_name_suffix not in ["jpg", "png", "gif", "jpeg", ]: | |
return JsonResponse({"message": "Wrong file format"}) | |
path = os.path.join( | |
settings.MEDIA_ROOT, | |
'tinymce', | |
) | |
# If there is no such path, create | |
if not os.path.exists(path): | |
os.makedirs(path) | |
file_path = os.path.join(path, file_obj.name) | |
file_url = f'{settings.MEDIA_URL}tinymce/{file_obj.name}' | |
if os.path.exists(file_path): | |
return JsonResponse({ | |
"message": "file already exist", | |
'location': file_url | |
}) | |
with open(file_path, 'wb+') as f: | |
for chunk in file_obj.chunks(): | |
f.write(chunk) | |
return JsonResponse({ | |
'message': 'Image uploaded successfully', | |
'location': file_url | |
}) | |
return JsonResponse({'detail': "Wrong request"}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Project/urls.py | |
# Add this to your project/urls.py | |
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) | |
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Make sure these variables are set. | |
STATIC_URL = '/static/' | |
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] | |
MEDIA_URL = '/media/' | |
MEDIA_ROOT = os.path.join('media') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// place this file inside of your static folder with name 'tinyInject.js' | |
var script = document.createElement('script'); | |
script.type = 'text/javascript'; | |
script.src = "https://cdn.tiny.cloud/1/u6d6drp5f5nqzvqu6eujg1dnek4vrscdre339fvjpf0ik7bw/tinymce/5/tinymce.min.js" | |
document.head.appendChild(script); | |
script.onload = function(){ | |
tinymce.init({ | |
selector: 'textarea', // change this value according to your HTML | |
// For more info regarding local upload in tinymce https://www.tiny.cloud/docs/demo/local-upload/ | |
images_upload_url: '/upload_image/', // Image upload address in Django route | |
height: 456, | |
plugins: [ | |
'advlist autolink link image lists charmap print preview hr anchor pagebreak', | |
'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking', | |
'table emoticons template paste help maxchars' | |
], | |
toolbar: 'fullscreen | undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' + | |
'bullist numlist outdent indent | link image | print preview media fullpage | ' + | |
'forecolor backcolor emoticons | uploadimage help ', | |
paste_data_images: true, | |
menu: { | |
favs: {title: 'My Favorites', items: 'code visualaid | searchreplace | emoticons'} | |
}, | |
menubar: 'favs file edit view insert format tools table help', | |
content_css: 'css/content.css' | |
}) | |
} |
i am facing http error 404 while uploading the file
I am also getting 404 while uploading
Tank you ♥
worked for me
can is use it in my products ?
Tank you ♥ worked for me can is use it in my products ?
Feel free to use it anywhere you wish 😊
Hi,
My image URL after enter again on form with tiny mce has wrong URL, it has "/admin" in it, but it is configured with:
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
Django is 5.0.3.
What is wrong.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice! One additional note: if you run tinymce in the admin you just specify MEDIA_URL in settings.py like this otherwise the pic will not be found:
MEDIA_URL = '/admin/media/'