如果没有给出图像,则 Django 模型函数保存图像字段 = 异常
Posted
技术标签:
【中文标题】如果没有给出图像,则 Django 模型函数保存图像字段 = 异常【英文标题】:Django model function to save ImageField if none image given = execption 【发布时间】:2019-03-31 19:05:22 【问题描述】:我有一个 Django 模型函数来正确保存图像。目前看来 Django-SmartFields 在那一点上有问题,请参阅:https://github.com/lehins/django-smartfields/issues/17 并且 sorl 无法正常工作,不知道为什么。 所以我很快写下了这个:
models.py
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(verbose_name="Title", max_length=40)
content = models.TextField(verbose_name="Content", max_length=5000)
tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True)
category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
postattachment = fields.FileField(
verbose_name="Attachment",
blank=True,
null=True,
upload_to=get_file_path_user_uploads,
validators=[file_extension_postattachment, file_size_postattachment]
)
postcover = fields.ImageField(
verbose_name="Cover",
blank=True,
null=True,
upload_to=get_file_path_user_uploads,
validators=[default_image_size, default_image_file_extension]
)
up_vote = models.IntegerField(verbose_name='Post Up-Vote(s)', default=0)
down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)
published_date = models.DateField(auto_now_add=True, null=True)
def save(self, *args, **kwargs):
imageTemproary = Image.open(self.postcover)
outputiostream = BytesIO()
imageTemproaryResized = imageTemproary.resize((700, 525))
imageTemproaryResized.save(outputIoStream, format='JPEG', quality=85)
outputIoStream.seek(0)
self.postcover = InMemoryUploadedFile(outputIoStream, 'ImageField',
"%s.jpeg" % self.postcover.name.split('.')[0], 'image/jpeg',
sys.getsizeof(outputIoStream), None)
super(Post, self).save(*args, **kwargs)
但如果我现在想通过我的表单清除图片,我会收到以下错误:
“postcover”属性没有与之关联的文件。
完整的跟踪:
Internal Server Error: /post/1/edit/
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/app/app_Accounts/decorators.py", line 33, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/ratelimit/decorators.py", line 30, in _wrapped
return fn(*args, **kw)
File "/app/app/views.py", line 473, in post_edit
post.save()
File "/app/app/models.py", line 173, in save
imageTemproary = Image.open(self.postcover)
File "/usr/local/lib/python3.6/site-packages/PIL/Image.py", line 2638, in open
fp.seek(0)
File "/usr/local/lib/python3.6/site-packages/django/core/files/utils.py", line 20, in <lambda>
seek = property(lambda self: self.file.seek)
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/files.py", line 41, in _get_file
self._require_file()
File "/usr/local/lib/python3.6/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 'postcover' attribute has no file associated with it.
确实。对此行为有快速解决方法吗?
提前谢谢
【问题讨论】:
请显示您的错误堆栈跟踪和models.py的全部内容 我刚刚更新了帖子 【参考方案1】:为什么你不能检查图像是否存在
import os //added
def save(self, *args, **kwargs):
super(Post, self).save(*args, **kwargs)
if self.postcover:
if os.path.exists(self.postcover.path): //this was added
imageTemproary = Image.open(self.postcover)
outputIoStream = BytesIO()
imageTemproaryResized = imageTemproary.resize((700, 525))
imageTemproaryResized.save(outputIoStream, format='JPEG', quality=85)
outputIoStream.seek(0)
self.postcover = InMemoryUploadedFile(outputIoStream, 'ImageField',
"%s.jpeg" % self.postcover.name.split('.')[0], 'image/jpeg',
sys.getsizeof(outputIoStream), None)
super(Post, self).save(*args, **kwargs)
【讨论】:
@Venom 对不起什么?只需用上面的替换模型保存 好吧,我做到了;)但没有任何改变。我可以将新图像保存到现场,但我无法清除其中的数据......所以我仍然和以前一样......首先很抱歉造成误解。到目前为止,谢谢。 好的,这再次以某种方式有所帮助,我能够保存该字段,但图像不会调整大小或转换为 jpeg。现在它的反应就像我根本不会使用你的台词......就像 Django Build-In 流程 似乎如果 os.path.exists(self.postcover.url)以上是关于如果没有给出图像,则 Django 模型函数保存图像字段 = 异常的主要内容,如果未能解决你的问题,请参考以下文章