gpt4 book ai didi

python - 如何覆盖 django 文件?

转载 作者:行者123 更新时间:2023-12-01 07:15:57 26 4
gpt4 key购买 nike

我有一个裁剪用户图像的函数,但我不希望模型有 2 个字段,因此我创建了一个覆盖原始文件的函数,我注意到该函数在普通文件上运行良好,但是当我添加该函数时到查看新文件已创建,但在媒体目录中甚至不是指定的文件夹,那么我如何通过 Django 覆盖文件?

模型.py

# defining directory for every patient
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/patient_<id>/<filename>
return 'patient_{0}/{1}'.format(instance.patient.id, filename)

class UploadedImages(models.Model):
patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images')
pre_analysed = models.ImageField(upload_to = user_directory_path ,
verbose_name = 'Image')
upload_time = models.DateTimeField(default=timezone.now)

裁剪功能:

import os
from PIL import Image

def crop(corrd, file ,path,pk):

image = Image.open(file) #To open the image as file.path won't open
path_1 , fn = os.path.split(path) #which is MEDIA_ROOT/and <filename>
patient_dir = 'patient_{}'.format(pk) #to get the user directory
path_ = path_1+patient_dir+fn #MEDIA_ROOT/patient_<id>/<filename>
cropped_image = image.crop(corrd)
resized_image = cropped_image.resize((384, 384), Image.ANTIALIAS)
resized_image.save(path_)

return path_

View .py

if form.is_valid():
image = form.save(commit=False)
x = float(request.POST.get('x'))
y = float(request.POST.get('y'))
w = float(request.POST.get('width'))
h = float(request.POST.get('height'))
print(x)
print(y)
print(w)
print(h)
crop((x,y,w+x,y+h),image.pre_analysed,image.pre_analysed.path)
image.patient = patient
messages.success(request,"Image added successfully!")
image.save()

表单.py

class ImageForm(ModelForm):
x = forms.FloatField(widget=forms.HiddenInput())
y = forms.FloatField(widget=forms.HiddenInput())
width = forms.FloatField(widget=forms.HiddenInput())
height = forms.FloatField(widget=forms.HiddenInput())

class Meta:
model = UploadedImages
fields = ('pre_analysed', 'x', 'y', 'width', 'height', )

那么我需要在这里做什么呢?提前致谢。

最佳答案

.path获取的路径是相对于您的MEDIA_ROOT文件夹的,这可能会阻止您的裁剪函数open() 图像文件。

然后您可以在 MEDIA_ROOT 中的某个位置创建一个新的裁剪文件。请务必使用os.makedirs()创建此处和文件之间的所有目录。另外,我没有看到您将从 crop() 返回的路径保存回 ImageField

关于python - 如何覆盖 django 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57947179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com