[英]How can I use user uploaded files in my templates? (django)
So far I made it to the part where a user uploads an image but how can I use those images which are located in my media folder? 到目前为止,我已经进入了用户上传图像的部分,但是如何使用位于我的媒体文件夹中的图像? Here is what I tried :
这是我尝试过的:
my view: 我的观点:
#I even tried to import MEDIA_ROOT to use it in my template...
#from settings import MEDIA_ROOT
def home(request):
latest_images = Image.objects.all().order_by('-pub_date')
return render_to_response('home.html',
#{'latest_images':latest_images, 'media_root':MEDIA_ROOT},
{'latest_images':latest_images,},
context_instance=RequestContext(request)
)
my model: 我的模特:
class Image(models.Model):
image = models.ImageField(upload_to='imgupload')
title = models.CharField(max_length=250)
owner = models.ForeignKey(User)
pub_date = models.DateTimeField(auto_now=True)
my template: 我的模板:
{% for image in latest_images %}
<img src="{{ MEDIA_ROOT }}{{ image.image }}" width="100px" height="100px" />
{% endfor %}
and my settings.py MEDIA_ROOT and URL: 和我的settings.py MEDIA_ROOT和URL:
MEDIA_ROOT = '/home/tony/Documents/photocomp/photocomp/apps/uploading/media/'
MEDIA_URL = '/media/'
So again here is what I am trying to do: Use those images in my templates! 所以这就是我想要做的:在我的模板中使用这些图像!
If you use the url
attribute, MEDIA_URL
is automatically appended. 如果使用
url
属性, MEDIA_URL
自动附加MEDIA_URL
。 Use name
if you want the path without MEDIA_URL
. 如果您想要没有
MEDIA_URL
的路径,请使用name
。 So all you need to do is: 所以你需要做的就是:
<img src="{{ some_object.image_field.url }}">
On development machine, you need to tell the devserver to serve uploaded files 在开发机器上,您需要告诉devserver提供上传的文件
# in urls.py
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
{# in template, use sorl-thumbnail if your want to resize images #}
{% with image.image as img %}
<img src="{{ img.url }}" width="{{ img.width }}" height="{{ img.height }}" />
{% endwith %}
# furthermore, the view code could be simplified as
from django.shortcuts import render
def home(request):
latest_images = Image.objects.order_by('-pub_date')
return render(request, 'home.html', {'latest_images':latest_images})
On production environment using normal filesystem storage, ensure the webserver has permission to write to MEDIA_ROOT. 在使用普通文件系统存储的生产环境中,确保Web服务器具有写入MEDIA_ROOT的权限。 Also configure the webserver to read
/media/filename
from correct path. 还要将Web服务器配置为从正确的路径读取
/media/filename
。
ImageField() has an url
attribute so try: ImageField()有一个
url
属性,所以尝试:
<img src="{{ MEDIA_URL }}{{ image.image.url }}" />
You could also add a method to your model like this to skip the MEDIA_ROOT part: 您还可以像这样向模型添加方法以跳过MEDIA_ROOT部分:
from django.conf import settings
class Image(...):
...
def get_absolute_url(self):
return settings.MEDIA_URL+"%s" % self.image.url
Also I'd use upload_to like this for sanity: 另外我会像上面这样使用upload_to来保持理智:
models.ImageField(upload_to="appname/classname/fieldname")
Try these settings: 试试这些设置:
import socket
PROJECT_ROOT = path.dirname(path.abspath(__file__))
# Dynamic content is saved to here
MEDIA_ROOT = path.join(PROJECT_ROOT,'media')
if ".example.com" in socket.gethostname():
MEDIA_URL = 'http://www.example.com/media/'
else:
MEDIA_URL = '/media/'
# Static content is saved to here
STATIC_ROOT = path.join(PROJECT_ROOT,'static-root') # this folder is used to collect static files in production. not used in development
STATIC_URL = "/static/"
STATICFILES_DIRS = (
('', path.join(PROJECT_ROOT,'static')), #store site-specific media here.
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
For Django version 2.2., try the following: 对于Django 2.2版,请尝试以下操作:
#You need to add the following into your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
Your URL mapping
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #add this
# And then use this in your html file to access the uploaded image
<img src="{{ object.image_field.url }}">
You have to make the folder containing the uploaded images "web accessible", ie either use Django to serve static files from the folder or use a dedicated web server for that. 您必须使包含上传图像的文件夹“可访问Web”,即使用Django从文件夹中提供静态文件或使用专用Web服务器。
Inside your template code, you have to use proper MEDIA_URL
values. 在模板代码中,您必须使用正确的
MEDIA_URL
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.