如何在 Django 表单实用程序中实现 sorl 缩略图?
所以表单实用程序文档是这样描述它的 ImageWidget 的:
(Thumbnails only available if sorl-thumbnail is installed; otherwise the full-size image is displayed).
但是,我似乎无法实现它。我尝试在模型中使用 sorl 的 ImageField,它破坏了 form-utils 的 ImageWidget,当我在模板中只有这样时,我无法在模板中使用它:
<li class="field_upload">
{{ form.image.errors }}
<label for="id_image" class="top">{{ form.image.label }}</label>
{{ form.image }}
</li>
form utils 有一个选项说:
ImageWidget accepts a keyword argument, template. This is a string defining how the image thumbnail and the file input widget are rendered relative to each other. The template string should contain variable interpolation markers %(input)s and %(image)s. The default value is %(input)s
%(image)s
代码如下:
pic = forms.ImageField(
widget=ImageWidget(template='%(image)s<br />%(input)s'))
但我还是想不通。
请您参考如下方法:
在您的表单类定义中,您似乎将 ImageField 命名为 pic,但随后在您的模板中,您试图使用 引用该字段表单.image.
现在尝试使用标准的 Django 表单渲染器,将 {{form}} 放入您的模板中——如果可行,那么您就知道这只是您的模板存在问题。
SORL 缩略图库应该只需要在您的 Django 项目的 Python 路径(以及 Python 图像库)上可以访问。
要检查这些库是否可用于您的 Django 项目,请转到项目的根目录并运行...
$ python manage.py shell
>> import sorl.thumbnail
>> import PIL
如果这些导入都没有抛出 ImportError,则它们已正确安装。
此外,可能还包含更多代码,例如您在
forms.py 中定义的整个表单。
