我有一个带有图像区域的模型,我在保存图像之前执行所有类型的自定义逻辑。例如,我调整图像大小并将其上传到服务器。然后我将它的路径链接到文件名。
所以我不需要Django来保存图像,它会覆盖我自定义尺寸的图像。
我想做的是阻止django imagefield自动将图像上传到服务器。有可能这样做吗?
更新了代码:
型号:
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)
查看:
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: .....
处理文件上传过程的函数。它处理我需要的所有进程,创建适当大小的文件并将其放在目录中。问题是,当实例由django保存时,它会自己创建文件,因此我有2个文件,并且使用了错误的文件。 我只想将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
表格:
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']
答案 0 :(得分:1)
我会尝试覆盖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
然后在你的列表视图中:
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: .....