[英]Django Custom image upload field with dynamic path
I'm trying to create my own field type for uploading images, it won't be used in the django admin panel. 我正在尝试创建自己的字段类型来上传图像,它不会在django管理面板中使用。 I imagine the syntax would probably look something like: 我想,语法可能看起来像:
photo = CustomImageField(upload_to='images', width="200", height="200")
I want to be able to set the parameters in the field when I upload and save an image. 我希望能够在上传和保存图像时在字段中设置参数。 I've looked through the django documentation but I can't find anything about how to do this. 我查看了django文档但我找不到任何关于如何执行此操作的信息。 So basically, I want to be able to control where the image is uploaded to and the width and height parameters when the upload form is processed and the object is saved. 基本上,我希望能够控制上传图像的位置以及处理上传表单并保存对象时的宽度和高度参数。
I am using Django 1.2 我正在使用Django 1.2
Any help would be greatly appreciated :) 任何帮助将不胜感激 :)
You don't need a custom field for this. 您不需要自定义字段。 As the documentation shows, upload_to
can be a callable, which is passed the instance and returns a path which determines where the field is saved. 如文档所示, upload_to
可以是可调用的,它传递给实例并返回一个路径,该路径确定字段的保存位置。
I'm not sure what you mean about the width and height parameters. 我不确定你对宽度和高度参数的意思。 These are calculated from the image in any case. 这些是在任何情况下从图像计算出来的。 If you specify height_field
and width_field
in the field definition, the corresponding fields will be filled with the values of the image's height and width when the image is uploaded. 如果在字段定义中指定height_field
和width_field
,则在上载图像时,将使用图像的高度和宽度值填充相应的字段。
Your can change the storage of a FileField using the location property. 您可以使用location属性更改FileField的存储空间。
form_name.photo.storage.location = upload_dir_path
It works for the FileField and maybe it will also work for your custom image field if you inherit the Django's ImageField. 它适用于FileField,如果你继承了Django的ImageField,它也可能适用于你的自定义图像字段。
all info for uploading: 所有上传信息:
http://docs.djangoproject.com/en/dev/topics/files/ http://docs.djangoproject.com/en/dev/topics/files/
and info on resizing 和调整大小的信息
resize image on save 保存时调整图像大小
i'll hope it helps 我希望它有所帮助
EDIT: all you need i think is: http://code.google.com/p/django-stdimage/ but i don't know if it works on current version. 编辑:我认为你只需要: http : //code.google.com/p/django-stdimage/但我不知道它是否适用于当前版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.