【发布时间】:2017-04-09 21:45:21
【问题描述】:
我有两种上传图片的方法。 1是从用户的文件中选择图像,另一种是通过URL上传图像。
模型
class Post(models.Model):
...
image = models.FileField(null=True, blank=True)
imageURL = models.URLField(null=True, blank=True)
def download_file_from_url(self):
print('DOWNLOAD') #prints "DOWNLOAD"
# Stream the image from the url
try:
request = requests.get(self, stream=True)
except requests.exceptions.RequestException as e:
# TODO: log error here
return None
if request.status_code != requests.codes.ok:
# TODO: log error here
return None
# Create a temporary file
lf = tempfile.NamedTemporaryFile()
# Read the streamed image in sections
for block in request.iter_content(1024 * 8):
# If no more file then stop
if not block:
break
# Write image block to temporary file
lf.write(block)
return files.File(lf)
html
<input id="id_image" type="file" name="image" /> <!--upload from file-->
{{ form_post.imageURL|placeholder:"URL" }} <!--url upload-->
从文件上传图像工作正常,用户只需点击输入并选择他们的文件。但是,当用户决定改用 URL 选项时。如何获取该 URL 字符串并将其设为 image 字段的值?
观看次数
...
if form_post.is_valid():
instance = form_post.save(commit=False)
if instance.imageURL:
instance.image = Post.download_file_from_url(instance.imageURL)
instance.save()
urls.py
...
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
...
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
【问题讨论】: