The admin or application of django uses the KindEditor Rich Text Editor, djangokindeditor
Because django's background management does not have a rich text editor, it looks ugly and the displayed pages are not beautiful, so what you see is what you get. Therefore, we need to introduce a third-party Rich Text Editor.
I have found a lot of documents and blogs to develop this function. Although some blogs are well-written, they are not comprehensive enough or cannot be understood, I sorted out some
Blog, so this Implementation decided to write this blog record. If you need it, you don't have to look for any information. At the same time, I will share it with you for reference. This time I used kindeditor rich.
Text Editor. The reason for choosing this editor is that it is fully functional and beautiful. The figure below shows kindeditor. Yes, there are so many features and the appearance is so nice.
Let's get started with using kindeditor in django.
Use in applications
Step 1:
Download kindeditor from the official website
After the download, delete the files that are not available, such as asp, asp.net, jsp, and php. Which are useless in django.
Step 2: Introduce the deleted file to your project. Static/js/editor/in the root directory/
Step 3: Introduce the js file of kindeditor into the webpage for the rich text editor,
<Script src = "/static/js/editor/kindeditor/kindeditor-all-min.js"> </script> <script src = "/static/js/editor/kindeditor/lang/zh-CN.js"> </script> <script src = "/static/js/editor/kindeditor/themes/default/default.css"> </script> <script> KindEditor. ready (function (k) {window. editor = k. create ('# editor_id', {resizeType: 1, allowPreviewEmoticons: false, allowImageRemote: false, {# Processing url #} uploadJson: '/upload/kindeditor ',});}) </script>
View Code
Introduced in my project, uploadJson is the url address of the uploaded file, which depends on how your url is configured and changed. The following describes url configuration.
Step 4: add an id = editor_id to the textarea of thml, which is the rich text editing box. This id is used in js in the previous step. note this.
<textarea id="editor_id" name="content" style="height: 400px" >{{ text }}</textarea>
View Code
The rich text editing box has been displayed. The configuration in django is shown below.
Configure in django
Step 1: configure the static file upload directory. The files uploaded in the editor will be saved here.
MEDIA_URL = '/static/media/'MEDIA_ROOT = os.path.join(BASE_DIR, "static/media")
View Code
Step 2: Configure in the project's urls configuration file
Step 3: Create a module named uploads. py in your application,
In my blog application, copy the following code to the file after creation.
From django. http import HttpResponsefrom django. conf import settingsfrom django. views. decorators. csrf import csrf_exemptimport osimport uuidimport jsonimport datetime as dt @ csrf_exemptdef upload_image (request, dir_name): result = {"error": 1, "message": "Upload error"} files = request. FILES. get ("imgFile", None) if files: result = image_upload (files, dir_name) return HttpResponse (json. dumps (result), content_type = "application/json") # create def upload_generation_dir (dir_name): today = dt. datetime. today () dir_name = dir_name + '/% d/' % (today. year, today. month) if not OS. path. exists (settings. MEDIA_ROOT + dir_name): OS. makedirs (settings. MEDIA_ROOT + dir_name) return dir_name # Image Upload def image_upload (files, dir_name): # the file type allow_suffix = ['jpg ', 'png', 'jpeg ', 'gif', 'bmp ', 'zip', "swf", "flv", "mp3", "wav", "wma", "wmv", "mid ", "avi", "mpg", "asf", "rm", "rmvb", "doc", "docx", "xls", "xlsx", "ppt ", "htm", "html", "txt", "zip", "rar", "gz", "bz2"] file_suffix = files. name. split (". ") [-1] if file_suffix not in allow_suffix: return {" error ": 1," message ":" incorrect image format "} relative_path_file = upload_generation_dir (dir_name) path = OS. path. join (settings. MEDIA_ROOT, relative_path_file) if not OS. path. exists (path): # create a directory OS if the directory does not exist. makedirs (path) file_name = str (uuid. uuid1 () + ". "+ file_suffix path_file = OS. path. join (path, file_name) file_url = settings. MEDIA_URL + relative_path_file + file_name open (path_file, 'wb '). write (files. file. read () return {"error": 0, "url": file_url}
View Code
Step 4: configure the url in the Application
Import the previously written View File uploads. py to the application's urls. py file.
From blog. uploads import upload_image
Url (R' ^ upload /(? P <dir_name> [^/] +) $ ', upload_image, name = 'upload _ image '),
from blog.uploads import upload_imageurlpatterns = [ url(r'^upload/(?P<dir_name>[^/]+)$', upload_image, name='upload_image'),]
View Code
In the preceding steps, the rich text editor can be used normally, including uploading images and videos.
Next let's take a look at how to use it in admin background management.
First, create a config. js file under the kindeditor directory we downloaded before and write this code, which is the same as that used in the application before.
KindEditor. ready (function (k) {window. editor = k. create ('# id_text', {# note that text = models is used in the model class. the id of TextField () is id_text. If it is an advance field type, you can check it in the browser and get the id resizeType: 1, allowPreviewEmoticons: false, allowImageRemote: false, uploadJson: '/upload/kindeditor', # This is the url width for processing the uploaded image Background: '800px ', height: '400px ',});})
KindEditor.ready(function (k) { window.editor = k.create('#id_text',{ resizeType:1, allowPreviewEmoticons : false, allowImageRemote : false, uploadJson : '/upload/kindeditor', width:'800px', height:'400px', });})
View Code
We recommend that you comment out the csrf in the settings. py middleware. Otherwise, the post request may report an error. In fact, this function is not very useful.
Next, you need to register the model class in admin. py. Introduce the js file of kindeditor to admin.
Import the model class. Here, my model class is Post. You can modify the class according to your model class. The original registration method such as # admin. site. register (Post) is commented out directly,
From django. contrib import adminfrom. models import * # Register your models here. # admin. site. register (Post) @ admin. register (Post) class PostAdmin (admin. modelAdmin): list_display = ['title'] class Media: # Add a js file to the HTML file in the management background, each path will append STATIC_URL/js = ('/static/js/editor/kindeditor/itor', '/static/js/editor/kindeditor/zh_CN.js ', '/static/js/editor/kindeditor/config. js ',)
View Code
My model class is like this. The rich text editor is used for the text field.
Because the code written by each person may be different, it is not completely common in some places, so you have to modify it yourself. The first time I used kinddetior, it was a great deal of effort. I read countless blogs and worked together.