如何在管理员中使用 django-ckeditor 在服务器上上传文件和浏览器文件?

Posted

技术标签:

【中文标题】如何在管理员中使用 django-ckeditor 在服务器上上传文件和浏览器文件?【英文标题】:How to use django-ckeditor to upload files and browser files on server in admin? 【发布时间】:2016-02-15 05:37:51 【问题描述】:

我被这个问题困扰了一整天。

我已经仔细阅读了github上django-ckeditor的文档,但是不够详细。而且给定的演示太复杂了。有没有更简单的实现上传和浏览的方法。如果可以在views.py,urls.py和setting.py中添加几行就可以实现了。

PS:我是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)

【问题讨论】:

【参考方案1】:

RichTextField('contents') 替换为RichTextUploadingField('contents') 并添加下一行

from ckeditor_uploader.fields import RichTextUploadingField

【讨论】:

【参考方案2】:

from ckeditor_uploader.fields import RichTextUploadingField

更改为content = RichTextUploadingField('contents')

然后将Update 添加到CKEDITOR_CONFIGS

看起来像

['Image', 'Update', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'],

【讨论】:

以上是关于如何在管理员中使用 django-ckeditor 在服务器上上传文件和浏览器文件?的主要内容,如果未能解决你的问题,请参考以下文章

Django-CKeditor:如何在模板中显示 RichTextFields

如何设置最大图像大小以在 django-ckeditor 中上传图像?

Django-CKEditor 图片上传

django-ckeditor使用

django-ckeditor 上传的图片的绝对路径

带有普通 Django 表单和引导程序的 Django-CKEditor