如何使用django-ckeditor在admin上的服务器上传文件和浏览器文件?

时间:2015-11-13 15:26:25

标签: python django ckeditor django-ckeditor

我整天都被这个问题困住了。

我已经仔细阅读了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)

2 个答案:

答案 0 :(得分:8)

替换if let paths = mode == 0 ? tvList.indexPathsForVisibleRows : tvGallery.indexPathsForVisibleRows { for path in paths { if let isNotNil = moProducts[path.row].data where moProducts[path.row].bidValid { if let cell = (mode == 0 ? tvList.cellForRowAtIndexPath(path) : tvGallery.cellForRowAtIndexPath(path)) as? SubClassCell { // do something here with the cell } } } } 上的RichTextField('contents') 并添加下一行

RichTextUploadingField('contents')

答案 1 :(得分:0)

from ckeditor_uploader.fields import RichTextUploadingField

更改为content = RichTextUploadingField('contents')

然后将Update添加到CKEDITOR_CONFIGS

看起来像

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