Search code examples
pythondjangockeditordjango-ckeditor

How to use django-ckeditor to upload files and browser files on server in admin?


I have been stuck by this problem for the whole day.

I have read the docs of django-ckeditor on github carefully, but it is not detailed enough. And the given demo is too complicated. Are there any easier way to implement the upload and browse.If it can be done just by adding several lines to views.py,urls.py and setting.py will make me easy to implement it.

PS:I am a newcomers to django.

urls.py

from django.conf.urls import include, url

urlpatterns = [

    url(r'^$', 'guitar.views.home', name='home'),


    url(r'^ckeditor/', include('ckeditor_uploader.urls')),

]

settings.py

import os


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)



MEDIA_URL = "image_upload/"
MEDIA_ROOT = os.path.join(BASE_DIR, "image_upload")




# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ')7sn#y%9dgm!pxl#c$ws_jld!%2lbvj5tg*jlqnaelc)+$bp*%'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []



INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap3',
    'guitar',
    'ckeditor',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'DemoGuitarProject.urls'


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'DemoGuitarProject.wsgi.application'



# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}



# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True






CKEDITOR_UPLOAD_SLUGIFY_FILENAME = False
CKEDITOR_JQUERY_URL = 'http://libs.baidu.com/jquery/2.0.3/jquery.min.js'
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_UPLOAD_SLUGIFY_FILENAME = True
CKEDITOR_UPLOAD_PATH = "image_upload/"


# config ckeditor
CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': (
            ['div', 'Source', '-', 'Save', 'NewPage', 'Preview', '-', 'Templates'],
            ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Print', 'SpellChecker', 'Scayt'],
            ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],
            ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
            ['Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript'],
            ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'],
            ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
            ['Link', 'Unlink', 'Anchor'],
            ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'],
            ['Styles', 'Format', 'Font', 'FontSize'],
            ['TextColor', 'BGColor'],
            ['Maximize', 'ShowBlocks', '-', 'About', 'pbckcode'],
        ),
    }
}

views.py

from django.shortcuts import render


def home(request):

    return render(request, 'home.html')

models.py

# coding:utf-8
from django.template.defaultfilters import slugify
from django.db import models
from ckeditor.fields import RichTextField


class Article(models.Model):
    title = models.CharField('title', max_length=256)
    content = RichTextField('contents')
    pub_date = models.DateTimeField('express_time', auto_now_add=True, editable=True)
    update_time = models.DateTimeField('update_time',auto_now=True, null=True)


    def __str__(self):
        return self.title      



class Category(models.Model):

    name = models.CharField(max_length=128, unique=True)

    def __str__(self):
        return self.name

admin.py

from django.contrib import admin
from .models import Article, Category



admin.site.register(Article)
admin.site.register(Category)

Solution

  • Replace RichTextField('contents') on RichTextUploadingField('contents') and add next line

    from ckeditor_uploader.fields import RichTextUploadingField