首页 > 解决方案 > How to get ckeditor field value in modelform after submit in Django2.1?

问题描述

  1. I have installed ckeditor.
  2. Placed "path('ckeditor/', include('ckeditor_uploader.urls'))," in urls.py
  3. Placed "'ckeditor'," in INTALLED_APPS in settings.py
  4. Placed

     ##  CKEDITOR CONFIGURATION ##
     ####################################
     CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'
    
     CKEDITOR_UPLOAD_PATH = 'uploads/help/'
     CKEDITOR_IMAGE_BACKEND = "pillow"
    
     CKEDITOR_CONFIGS = {
            'default': {
                  'toolbar': None,
                  'height':100,
                  'width':500,
             },
     }
    
    ###################################
    

    at the end of file in settings.py

  5. models.py :

    from ckeditor.fields import RichTextField
    from django.db import models
    class Help(models.Model):
       title = models.CharField(max_length=255)
       description = RichTextField(blank=True, null=True) #models.TextField()
       class Meta:
           managed = False
           db_table = 'help'
       def __str__(self):
           return self.title
    
  6. forms.py

    from ckeditor.widgets import CKEditorWidget
    from django import forms
    class HelpForm(ModelForm):
        description = forms.CharField(widget=CKEditorWidget())
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
    
        class Meta:
            model = Help
            exclude = ('created_by', 'updated_by', 'created', 'updated')
    
  7. help.html

    {% load i18n static widget_tweaks %}
    <form id="newFrm" method="post" novalidate>
    {% csrf_token %}
    {{ form.media }}
    
      <div class="col-lg-6 col-md-8 col-sm-12 col-xs-24">
        <div class="form-group">
          <label for="">description <span class="required">*</span></label>
           {% if form.title.errors %}
            {% render_field form.description class="form-control ckeditor error" placeholder="Description" %}
            <div class="error-msg show  form-error">
            {{ form.description.errors}}
            </div> 
            {% else %}
            {% render_field form.description class="form-control ckeditor" placeholder="Description" %}
            {% endif %} 
        </div>
      </div>
    

Question: I am not getting the POST value of description after form submit(in views.py). Any help will be appreciated. Thanks in advance.

标签: pythonckeditormodelform

解决方案


I found the solution. Please put below script in your code.

    for (var i in CKEDITOR.instances) {
            CKEDITOR.instances[i].on('change', function() { 
                    CKEDITOR.instances[i].updateElement() });
    }

This code will update the raw data of ckeditor in to related textarea. Now on submit the form, you will get the data in POST.


推荐阅读