简体   繁体   English

防止Django imageField上传/保存图像

[英]Prevent Django imageField from uploading / saving image

I have a model with an image field and I perform all kind of custom logic before image is saved. 我有一个带有图像字段的模型,并且在保存图像之前执行了各种自定义逻辑。 For example, I resize image and upload it to the server. 例如,我调整图像大小并将其上传到服务器。 Then I link it's path to the filename. 然后,我将其路径链接到文件名。

So I don't need Django to save the image, which it does overwriting my custom sized image. 因此,我不需要Django保存图像,它会覆盖我自定义尺寸的图像。

What I would like to do, is prevent django imagefield from automatically uploading image to the server. 我想做的是防止django imagefield自动将图像上传到服务器。 Is it possible to do this ? 是否有可能做到这一点 ?

Updated with code: 更新的代码:

Model: 模型:

class Document(models.Model):
    myField = models.CharField(max_length=500)
    image_main = models.ImageField(blank=True, upload_to=change_filename_to_slug)
    image_thumbsize_big = models.ImageField(blank=True)
    image_thumbsize_small = models.ImageField(blank=True)

View: 视图:

def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            instance        = form.save(commit=False)  # Creates a modifiable instance

            instance.save()
            return HttpResponseRedirect('/list/')
    else: .....

The function that handles the file upload process. 处理文件上传过程的功能。 It handles all the process I need, creates file of proper size and put it in directory. 它处理了我需要的所有过程,创建了适当大小的文件并将其放在目录中。 Problem is that when the instance is saved by django, it creates the file on it's own, and thus I have 2 files and the wrong one is used. 问题是,当实例由django保存时,它自己创建了文件,因此我有2个文件,并且使用了错误的文件。 I would only like to short-circuit django and prevent imagefield form creating it's file: 我只想短路django并阻止imagefield表单创建它的文件:

def change_filename_to_slug(instance, filename):

    file = instance.image_main
    # Variables
    save_media_dir = instance.mediaUrl + instance.saveImagepath  # Passed by model
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + save_media_dir
    im = Image.open(file)
    slug = slugify(instance.myField, allow_unicode=True)
    finalpath = None
    has_iterated = 0

for key, value in sizes.items():
    im_reset = im
    im_reset = im_reset.resize(value, Image.ANTIALIAS)
    save_dir = base_dir + slug + key
    field_file_name = save_media_dir


    if im.format.lower() == 'png':
        # Save in folder : no need to save again
        im_reset.save(save_dir + '.png', compress_level=png_compress, format='PNG')  
        # Save names in fields:
        if has_iterated == 0: finalpath =  'dir/' +  slug + key + '.png'  
        if has_iterated == 1: instance.image_thumbsize_big = field_file_name + slug + key + '.png'
        if has_iterated == 2: instance.image_thumbsize_small = field_file_name + slug + key + '.png'
        has_iterated += 1


return finalpath

The form: 表格:

from .models import Document
from django.forms import ModelForm

class DocumentForm(ModelForm):
    class Meta:
        model = Document
        fields = ['myField', 'image_main', 'image_thumbsize_big', 'image_thumbsize_small']

I would try and overwrite the Form's save method: 我会尝试覆盖Form的save方法:

class DocumentForm(ModelForm):

    def __init__(self, post_data, files_data):
        self.image_main_file = files_data.get('image_main', None)
        return super(DocumentForm, self).__init__(post_data, files_data)

    def save(self, force_insert=False, force_update=False, commit=True):
        instance = super(DocumentForm, self).save(commit=False)
        # do your image magic here, e.g.
        # instance.image_thumbsize_big = field_file_name + slug + key + '.png'

        # you can access your main file with: self.image_main_file
        if commit:
            instance.save()
        return instance

and then in your list-view: 然后在您的列表视图中:

def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            instance        = form.save(commit=True)
            return HttpResponseRedirect('/list/')
    else: .....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM