使用 filerImageField 上传图片

Posted

技术标签:

【中文标题】使用 filerImageField 上传图片【英文标题】:upload image using filerImageField 【发布时间】:2017-05-03 18:37:07 【问题描述】:

我得到了简单的表格。我想保存图像而不是在模板中渲染它。 表格工作正常。所有值都被存储和呈现。 当我单击“选择图像”时,我被重定向到 admin/filer/folder/ 我可以选择图像并保存它。比我挑不出来。如果我点击它,我只能更改设置。如果我将图像拖放到模板中的字段中,当我提交表单“选择一个有效的选择”时会出现错误。

settings.py

import os
gettext = lambda s: s
DATA_DIR = os.path.dirname(os.path.dirname(__file__))
"""
Django settings for bloger project.

Generated by 'django-admin startproject' using Django 1.8.17.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

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


# 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 = '_g$(y(@55v1i@a22$tgnpermt78(w!+(*pfei3483+&h)o1@xb'

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

ALLOWED_HOSTS = []


# Application definition





    ROOT_URLCONF = 'bloger.urls'



    WSGI_APPLICATION = 'bloger.wsgi.application'


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




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

    LANGUAGE_CODE = 'en'

    TIME_ZONE = 'Europe/Ljubljana'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True


    # Static files (CSS, javascript, Images)
    # https://docs.djangoproject.com/en/1.8/howto/static-files/

    STATIC_URL = '/static/'
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(DATA_DIR, 'media')
    STATIC_ROOT = os.path.join(DATA_DIR, 'static')
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'bloger', 'static'),
    )
    SITE_ID = 1


    TEMPLATES = [
        
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'bloger', 'templates'),],
            'OPTIONS': 
                'context_processors': [
                    'django.contrib.auth.context_processors.auth',
        'django.contrib.messages.context_processors.messages',
        'django.core.context_processors.i18n',
        'django.core.context_processors.debug',
        'django.core.context_processors.request',
        'django.core.context_processors.media',
        'django.core.context_processors.csrf',
        'django.core.context_processors.tz',
        'sekizai.context_processors.sekizai',
        'django.core.context_processors.static',
        'cms.context_processors.cms_settings'
                ],
                'loaders': [
                    'django.template.loaders.filesystem.Loader',
        'django.template.loaders.app_directories.Loader',
        'django.template.loaders.eggs.Loader'
                ],
            ,
        ,
    ]


    MIDDLEWARE_CLASSES = (
        'cms.middleware.utils.ApphookReloadMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.locale.LocaleMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'cms.middleware.user.CurrentUserMiddleware',
        'cms.middleware.page.CurrentPageMiddleware',
        'cms.middleware.toolbar.ToolbarMiddleware',
        'cms.middleware.language.LanguageCookieMiddleware'
    )

    INSTALLED_APPS = (
        'djangocms_admin_style',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.admin',
        'django.contrib.sites',
        'django.contrib.sitemaps',
        'django.contrib.staticfiles',
        'django.contrib.messages',
        'cms',
        'menus',
        'sekizai',
        'treebeard',
        'djangocms_text_ckeditor',
        'filer',
        'easy_thumbnails',
        'djangocms_column',
        'djangocms_link',
        'cmsplugin_filer_file',
        'cmsplugin_filer_folder',
        'cmsplugin_filer_image',
        'cmsplugin_filer_utils',
        'djangocms_style',
        'djangocms_snippet',
        'djangocms_googlemap',
        'djangocms_video',
        'bloger',
        'colorful',
        'Styles',
        'Navigation',
        'Blog',
        'subscribing',
        'slideshow',
        'ckeditor',
        'ckeditor_uploader',
    )

    LANGUAGES = (
        ## Customize this
        ('en', gettext('en')),
    )

    CMS_LANGUAGES = 
        ## Customize this
        'default': 
            'public': True,
            'hide_untranslated': False,
            'redirect_on_fallback': True,
        ,
        1: [
            
                'public': True,
                'code': 'en',
                'hide_untranslated': False,
                'name': gettext('en'),
                'redirect_on_fallback': True,
            ,
        ],
    

    CMS_TEMPLATES = (
        ## Customize this
        ('fullwidth.html', 'Fullwidth'),
        ('sidebar_left.html', 'Sidebar Left'),
        ('sidebar_right.html', 'Sidebar Right'),
        ('blog.html', 'blog')
    )

    CMS_PERMISSION = True

    CMS_PLACEHOLDER_CONF = 

    DATABASES = 
        'default': 
            'ENGINE': 'django.db.backends.mysql',  # .sqlite3
            'NAME': 'Blog_cms',
            'HOST': 'localhost',
            'USER': 'root',
            'PASSWORD': 'tukiNIfore1991',
            'PORT': ''
        
    
    MIGRATION_MODULES = 

    

    THUMBNAIL_PROCESSORS = (
        'easy_thumbnails.processors.colorspace',
        'easy_thumbnails.processors.autocrop',
        'filer.thumbnail_processors.scale_and_crop_with_subject_location',
        'easy_thumbnails.processors.filters'
    )



    CKEDITOR_CONFIGS = 
        'default': 
            'skin': 'moono',
            # 'skin': 'office2013',
            'toolbar_Basic': [
                ['Source', '-', 'Bold', 'Italic']
            ],
            'toolbar_YourCustomToolbarConfig': [
                'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates'],
                'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'],
                'name': 'editing', 'items': ['Find', 'Replace', '-', 'SelectAll'],
                'name': 'forms',
                 'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
                           'HiddenField'],
                '/',
                'name': 'basicstyles',
                 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'],
                'name': 'paragraph',
                 'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-',
                           'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl',
                           'Language'],
                'name': 'links', 'items': ['Link', 'Unlink', 'Anchor'],
                'name': 'insert',
                 'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe'],
                '/',
                'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize'],
                'name': 'colors', 'items': ['TextColor', 'BGColor'],
                'name': 'tools', 'items': ['Maximize', 'ShowBlocks'],
                'name': 'about', 'items': ['About'],
                '/',  # put this to force next toolbar on new line
                'name': 'yourcustomtools', 'items': [
                    # put the name of your editor.ui.addButton here
                    'Preview',
                    'Maximize',

                ],
            ],
            'toolbar': 'YourCustomToolbarConfig',  # put selected toolbar config here
            # 'toolbarGroups': [ 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' ] ],
            # 'height': 291,
            # 'width': '100%',
            # 'filebrowserWindowHeight': 725,
            # 'filebrowserWindowWidth': 940,
            # 'toolbarCanCollapse': True,
            # 'mathJaxLib': '//cdn.mathjax.org/mathjax/2.2-latest/MathJax.js?config=TeX-AMS_HTML',
            'tabSpaces': 4,
            'extraPlugins': ','.join(
                [
                    # your extra plugins here
                    'div',
                    'autolink',
                    'autoembed',
                    'embedsemantic',
                    'autogrow',
                    # 'devtools',
                    'widget',
                    'lineutils',
                    'clipboard',
                    'dialog',
                    'dialogui',
                    'elementspath'
                ]),
        
    



    CKEDITOR_UPLOAD_PATH = "uploads/"
    CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'

views.py

def post_new(request):
    if request.method == "POST":
        form = BlogForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = BlogForm()
    return render(request, 'post_edit.html', 'form': form)

models.py

class Blog_post(CMSPlugin):
category = models.ForeignKey(Category)
style = models.ForeignKey(Blog_style)
title = models.CharField(max_length=200, default='title')
description = models.CharField(max_length=200,default='description')
image = FilerImageField(null=True, blank=True,)
text = RichTextField()
created_date = models.DateTimeField(
        default=timezone.now)
published_date = models.DateTimeField(
        blank=True, null=True)

forms.py

class BlogForm(forms.ModelForm):

    class Meta:
        model = Blog_post
        fields = ('category', 'style', 'title', 'description', 'image', 'text')

【问题讨论】:

【参考方案1】:

图像的路径是绝对路径。您需要提供一个相对路径,它将被添加到您的媒体文件夹中:

class Blog_post(CMSPlugin):
    category = models.ForeignKey(Category)
    style = models.ForeignKey(Blog_style)
    title = models.CharField(max_length=200, default='title')
    description = models.CharField(max_length=200,default='description')
    image = models.ImageField(upload_to='images/', null=True, blank=True)
    text = RichTextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

查看文档的示例:

class MyModel(models.Model):
    # file will be uploaded to MEDIA_ROOT/uploads
    upload = models.FileField(upload_to='uploads/')
    # or...
    # file will be saved to MEDIA_ROOT/uploads/2015/01/30
    upload = models.FileField(upload_to='uploads/%Y/%m/%d/')

【讨论】:

我已经试过了,还是不行。感谢您帮助我,还有其他想法吗? 你能检查一下媒体文件夹吗?图像是否在您指向的文件夹中创建? 不,它没有...我不确定问题出在哪里,我拥有所有权限。 提交后尝试打印表单,并在保存帖子对象之前检查图像字段的值。你得到了什么价值? 我得到一个图像名称和格式。但是当我点击保存时,img 没有保存。【参考方案2】:

我认为你混合了两件事:

    FilerFileFieldFilerImageField 直接在 models.py 中使用,如Django-Filer documentation 中所述 在 CKEDITOR 中使用 Filer:django-ckeditor-filebrowser-filer(很好地解释了实现here)

但是,您是对的,管理员之外的文件管理器似乎是 impossible,但 SteinRoberts 发布的 github 问题给了我解决方案:

首先,在模板 html 文件中添加 form.media ,就在 标记<form>% csrf_token %。然后扩展媒体类 你的ModelFormforms.py

class Media:
    extend = False
    css = 
        'all': [
            'filer/css/admin_filer.css',
        ]
    
    js = (
        'admin/js/core.js',
        'admin/js/jquery.js',
        'admin/js/jquery.init.js',
        'admin/js/admin/RelatedObjectLookups.js',
        'admin/js/actions.js',
        'admin/js/urlify.js',
        'admin/js/prepopulate.js',
        'filer/js/libs/dropzone.min.js',
        'filer/js/addons/dropzone.init.js',
        'filer/js/addons/popup_handling.js',
        'filer/js/addons/widget.js',
        'admin/js/related-widget-wrapper.js',
    )

【讨论】:

以上是关于使用 filerImageField 上传图片的主要内容,如果未能解决你的问题,请参考以下文章

vue移动端图片上传,可最多上传9张,使用webuploader插件

原生方式实现图片,文件上传,和使用ElmentUI使用Drag方式自动上传图片,手动上传图片

使用webuploader插件上传图片时如果正确 限制上传数量

快速创建VUE移动端上传图片功能

java web开发,上传图片并读取

html 表单上传图片