如何删除使用django-ckeditor上传的图片?

dohp0rv5  于 2023-10-21  发布在  Go
关注(0)|答案(3)|浏览(141)

我在Django管理界面的CKEditor中上传了一些图片。我可以通过点击编辑器中的“图像”按钮来浏览和选择图像,然后在弹出的窗口中点击“浏览服务器”。以下是弹出窗口的屏幕截图:

我的问题是:如何删除服务器上的图像?

kmynzznz

kmynzznz1#

不幸的是,这是事实。Django-ckeditor并没有为这个问题提供任何内置的解决方案。有关上传文件的信息不会存储在任何地方。
如果你想留住他们-你必须自己去做!
使用覆盖的 delete 方法创建适当的数据模型(或者使用任何可以为您处理文件删除的现成“智能字段”,Django delete FileField):

from django.db import models

class UploadedFile(models.Model):
    uploaded_file = models.FileField(upload_to=u"storage/")
    uploaded_at = models.DateField(editable=False, auto_now_add=True)

    def __str__(self):
        return os.path.basename(self.uploaded_file.path)

    def url(self):
        return self.uploaded_file.url

    def delete(self, *args, **kwargs):
        file_storage, file_path = self.uploaded_file.storage, self.uploaded_file.path
        super(UploadedFile, self).delete(*args, **kwargs)
        file_storage.delete(file_path)

提供您自己的“upload”(和可选的“browse”)视图的实现,它将用于记住交易:

from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from ckeditor_uploader.views import upload, browse
from .models import UploadedFile
import re

@staff_member_required
@csrf_exempt
def ckeditor_upload_wrapper(request, *args, **kwargs):
    response = upload(request, *args, **kwargs)

    if b"Invalid" not in response.content:
        try:
            matched_regex = re.search("callFunction\(\d, '(.*)'\);", str(response.content))
            file_location = matched_regex.group(1).lstrip(settings.MEDIA_URL)
            UploadedFile(uploaded_file=file_location).save()
        except Exception:
            pass
    return response

@staff_member_required
@csrf_exempt
@never_cache
def ckeditor_browse_wrapper(request, *args, **kwargs):
    return browse(request, *args, **kwargs)

更改urls.py中的默认重定向:

...
from app.views import ckeditor_upload_wrapper, ckeditor_browse_wrapper

urlpatterns = [
    url(r'^admin/', admin.site.urls),

    #url(r'^ckeditor/', include('ckeditor_uploader.urls')),
    url(r'^ckeditor/upload/', ckeditor_upload_wrapper, name='ckeditor_upload'),
    url(r'^ckeditor/browse/', ckeditor_browse_wrapper, name='ckeditor_browse'),
    ...
]

就这样现在如果你注册了新的扩展文件模型,你就可以直接在Django管理面板中浏览,搜索和删除上传的图片。
(This解决方案已在 Django 1.10 上实现,扩展名为 django-ckeditor 5.3

kqqjbcuj

kqqjbcuj2#

我担心这是不可能与ckeditor(至少我没有看到这样的功能开箱即用)。
您可以使用Django文件管理器
https://www.djangopackages.com/grids/g/file-managers/
例如,django-filebrowser

31moq8wy

31moq8wy3#

我正在使用此解决方案

class Post(TimeStampedModel):
    title = models.CharField('titulo', max_length=255)
    slug = models.SlugField(max_length=255, blank=True, unique=True)
    author = models.ForeignKey(User,
                               on_delete=models.SET_NULL,
                               blank=True,
                               null=True)
    content = RichTextUploadingField('conteudo', blank=True, null=True)
    post_date = models.DateField('data', blank=True, null=True)
    obs = models.CharField('obs', max_length=255, blank=True, null=True)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-post_date']
        verbose_name = 'notícia'
        verbose_name_plural = 'notícias'

    def get_absolute_url(self):
        return resolve_url('core:post_detail', slug=self.slug)

    def get_exter_url(self):
        return resolve_url('external:post_detail', slug=self.slug)

    def get_firt_img(self):
        soup = BeautifulSoup(self.content, "html.parser")
        imgs = soup.find_all("img")
        return imgs[0]['src'] if len(imgs) > 0 else ''

    def get_link_imgs(self):
        soup = BeautifulSoup(self.content, "html.parser")
        imgs = soup.find_all("img")
        list_img = []
        for element in imgs:
            list_img.append(element['src'])

        return list_img

    def save(self, *args, **kwargs):
        if not self.slug:
            unique_slugify(self, self.title, slug_field_name='slug')

        super(Post, self).save(*args, **kwargs)

# signal Post
@receiver(post_delete, sender=Post)
def remov_to_imgs(sender, instance, **kwargs):
    for img in instance.get_link_imgs():
        _file = urllib.parse.unquote(str(settings.BASE_DIR)+img)
        # get thumb the img
        ext = '.'+''.join(_file.split('.')[-1])
        thumb = _file[:-len(ext)]+'_thumb'+ext
        exists = os.path.isfile(_file)
        if exists:
            if not Post.objects.filter(content__icontains=img).exclude(
                pk=instance.pk).exists():
                os.remove(_file)
                # thumb img
                if os.path.isfile(thumb):
                    os.remove(thumb)

相关问题