views.py
if request.is_ajax():
testpic = TestPic.objects.get(pk=1)
form = TestPicForm(request.POST, request.FILES, instance=testpic)
if form.is_valid():
form.save()
forms.py
class TestPicForm(forms.ModelForm):
class Meta:
from .models import TestPic
model = TestPic
fields = ('file', 'file_50',)
def save(self):
test_photo = super(TestPicForm, self).save()
file = user_photo.file
image = Image.open(file)
rotated_image = image.rotate(90, expand=True)
cropped_image = rotated_image.resize((300, 300), Image.ANTIALIAS)
cropped_50_image = rotated_image.resize((50, 50), Image.ANTIALIAS)
cropped_image.save(test_photo.file.path)
file.seek(0)
cropped_50_image.save(test_photo.file_50.path)
return user_photo
models.py
class TestPic(models.Model):
file = models.ImageField(null=True, blank=True, default=None, upload_to="photo/%Y/%m/%d")
file_50 = models.ImageField(null=True, blank=True, default=None, upload_to="photo/%Y/%m/%d")
此代码用于上传图像文件,将其调整为两个不同的大小并保存。
可悲的是,它仅在字段file_50
上有任何文件时有效。
换句话说,如果some_file_50.jpeg
字段上有文件file_50
,则可以上传图像文件,但是在django-admin中,{{ 1}}字段。(file_50
字段的文件名已更改。)但是file
的内容已更改。(我可以通过单击django-admin上的图像文件链接来查看这些更改) ,some_file_50.jpeg
不可更改。
当some_file_50.jpeg
字段上没有文件时,它将引发错误:
file_50
问题:如何解决?感谢您的阅读。
ADD追溯:
The 'file_50' attribute has no file associated with it.
ADD html,jquery ajax上传代码:
Internal Server Error: /accounts/crop/
Traceback (most recent call last):
File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\pythonDev\project\upward\chatkaboo\authapp\views.py", line 833, in crop
form.save()
File "D:\pythonDev\project\upward\chatkaboo\authapp\forms.py", line 182, in save
cropped_50_image.save(user_photo.file_50.path)
File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\db\models\fields\files.py", line 56, in path
self._require_file()
File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\db\models\fields\files.py", line 38, in _require_file
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'file_50' attribute has no file associated with it.
答案 0 :(得分:1)
看着您的save
方法,我看不到您将修改后的文件分配到模型的file_50
字段的位置。我认为您想做的事情类似于以下内容?
cropped_50_image = rotated_image.resize((50, 50), Image.ANTIALIAS)
# Assign cropped image to image_50 model field
user_photo.image_50 = cropped_50_image
user_photo.save()
这只是伪代码。在分配as discussed here之前,可能需要包装该文件以使其成为正确的Django文件。