Django is an excellent web development framework for Python stack. It is also the most widely used web development framework for Python stack. As to whether it is good enough or not, its own management background ORM function is very powerful, and a few lines of simple configuration can quickly have a strong management background. The only downside is that it doesn’t integrate a rich text editor. There are plenty of third-party packages that do, but they don’t seem to be very active in maintenance or upgrading, so I chose to integrate my own rich text editor for my Django-Happy-shop project!

Now that django-Happy-shop project is mentioned, I have the cheekiness to ask you for a star. The code is hosted in Gitee as an open source source. You can find it by searching the name.

HappyShop is a Django development third-party package, using Django + DRF + Vue development, with the front and back end of the gene separation, has a complete multi-specification product logic, integration of Alipay payment, only a simple configuration can be fast payment, can be quickly integrated into any Django project. To quickly get a simple mall function.

Anyway, why wangEditor?

First of all, because he is a very good rich text editor developed by the people, support native JS integration and VUE and other front-end excellent framework integration, the document is also very perfect, the most important is convenient to read Chinese documents, simple configuration, easy to use, and open source free!

Begin to integrate

Model data Description

There is a field content of commodity details in the commodity model, and the field selected is TextFiled, as shown below:

Content = models.TextField(” Product details “)

In admin.py we inherit ModelAdmin to achieve background management functions, as shown below, you can see the source code

@admin.register(HappyShopSPU)
class HappyShopSPUAdmin(HappyShopAdmin) :
    '''Admin View for HappyShopSPU'''
    list_display = ('get_title'.'get_main_picture'.'get_category'.'brand'.'is_new'.'sort'.'add_date')
Copy the code

With this code we have registered the model with the admin admin background!

Djangos ModelAdmin provides a Media source class to register the JS files and CSS files in the template, as shown below:

@admin.register(HappyShopSPU)
class HappyShopSPUAdmin(HappyShopAdmin) :
    '''Admin View for HappyShopSPU'''
    list_display = ('get_title'.'get_main_picture'.'get_category'.'brand'.'is_new'.'sort'.'add_date')...class Media:
        js = (
            'admin/js/vendor/jquery/jquery.min.js'.'https://cdn.jsdelivr.net/npm/wangeditor@latest/dist/wangEditor.min.js'.'happy_shop/js/weditor.js'
        )
Copy the code

Djangos jquery file comes with django by default. The second js connection to the external CDN is the editor JS file provided by wangEditor. The third weditor.js file is our own configuration file, the main front-end integration configuration functions are concentrated in weditor.js file! As follows:

$(document).ready(function () {
    // Create a rich text editor element node
    var wehtml = "<div id='wangcontent'></div>"
    // Get div
    var field_div = document.querySelectorAll(".field-content>div")
    field_div[0].insertAdjacentHTML('afterbegin'.' Merchandise details: ');
    field_div[0].insertAdjacentHTML('beforeend', wehtml);
    $(".field-content>div>label").attr('style'.'display:none')
    
    const E = window.wangEditor
    const editor = new E("#wangcontent")
    // Const editor = new E(document.getelementById ('div1'))
    const $text1 = $('#id_content')
    console.log($text1.val())
    editor.config.onchange = function (html) {
        // Step 2, monitor the changes and synchronize updates to the textarea
        $text1.val(html)
    }

    editor.config.height = 500
    // Set the server interface address
    editor.config.uploadImgServer = '/happy/upload_img/'
    editor.config.uploadFileName = 'spuImg'
    editor.create()
    editor.txt.html($text1.val())
    // Initialize the value of textarea
    $text1.val(editor.txt.html())
    $text1.attr("style"."display:none")})Copy the code

The interpretation of this code I don’t do too much, only detailed said, first of all, we all know that form the default django will have an id attribute, the attribute value in the form of id_ field combination, so we just need to put the content of the rich text editor assignment to submit id_content input box can be normal, this is the general logic, All that’s left is to run for it!

First we find the rich text edit block, which is in a.field-content module, and we find that block, Insert a rich text element

into the block as js. Then integrate the rich text editor with the wangEditor document and listen for the editor’s onchange event. I’m going to synchronize the contents of the rich text editor to the id_content form. One thing to be aware of here is that if you add content to the form, you should also echo it back to the rich text editor when you edit it, so you have to do this, Editor.txt.html ($text1.val()) = $text1.val();

For the rest of the code, refer directly to the wangEditor documentation, which is very clear!

Realize picture upload function

Upload.js: upload.js: upload.js

// Set the server interface address
editor.config.uploadImgServer = '/happy/upload_img/'
editor.config.uploadFileName = 'spuImg'
Copy the code

The first sentence is the url where the image was uploaded. The second sentence is the name value of the custom form;

Upload url corresponding view code is as follows, specific logic you can see the code, might be more clear than text, limiting the need to login to upload here, if further limit, we can limit the super tube permissions, this is perfect permissions 】 【 but I didn’t do so, and there is no limit to upload the file type, This is because the rich text editor has already set the image size and type by default in the previous section, of course, the value passed from the front end should never be trusted as the back end, to verify it, this will be handled in later versions, all extracted into the project configuration file!

class HappyShopUploadImage(LoginRequiredMixin, View) :
    "" The rich text editor will first check if there is a media/upload/ folder in the project root directory. Images stored in the media/upload/directory Returns the image path to "/ media/upload/file. PNG" wangEditor_v4 document: https://www.wangeditor.com/ "" "
    
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs) :
        return super().dispatch(*args, **kwargs)
    
    def post(self, request, *args, **kwargs) :
        import os
        import uuid
        file_data = request.FILES
        keys = list(file_data.keys())
        file_path = settings.BASE_DIR / 'media/upload/'
        if os.path.exists(file_path) is False:
            os.mkdir(file_path)
        Return the required data from the data
        data = []
        for key in keys:
            img_dict = {}
            file = file_data.get(f'{key}')
            Rename the file name
            names = list(os.path.splitext(file.name))
            names[0] = ' '.join(str(uuid.uuid4()).split(The '-'))
            file.name = ' '.join(names)
            new_path = os.path.join(file_path, file.name) 
            # start uploading
            with open(new_path, 'wb+') as f:
                for chunk in file.chunks():
                    f.write(chunk)
            # construct returns data
            img_dict['url'] = f'/media/upload/{file.name}'
            data.append(img_dict)
        context = {"errno": 0."data":data}
        return JsonResponse(context)
Copy the code

Finally, add the view URL to the application URL file as follows:

path('upload_img/', views.HappyShopUploadImage.as_view(), name="upload_img")
Copy the code

At this point, our rich text editor integration is successful, if there is not clear message consultation, or directly look at the source oh! Don’t forget Star!