4

到目前为止,我已经完成了用户上传图像的部分,但是如何使用位于我的媒体文件夹中的那些图像?这是我尝试过的:

我的观点:

#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)
                             )

我的模型:

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)

我的模板:

{% for image in latest_images %}
    <img src="{{ MEDIA_ROOT }}{{ image.image }}" width="100px" height="100px" />
{% endfor %}

和我的 settings.py MEDIA_ROOT 和 URL:

MEDIA_ROOT = '/home/tony/Documents/photocomp/photocomp/apps/uploading/media/'
MEDIA_URL = '/media/'

所以这就是我想要做的:在我的模板中使用这些图像!

4

5 回答 5

5

如果使用该url属性,MEDIA_URL则自动附加。如果name您想要没有MEDIA_URL. 所以你需要做的就是:

<img src="{{ some_object.image_field.url }}">
于 2012-04-13T14:01:12.547 回答
3

在开发机器上,您需要告诉开发服务器提供上传的文件

# 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})

在使用普通文件系统存储的生产环境中,确保网络服务器具有写入 MEDIA_ROOT 的权限。还将网络服务器配置为/media/filename从正确的路径读取。

于 2012-04-13T14:06:43.510 回答
2

ImageField() 有一个url属性,所以试试:

<img src="{{ MEDIA_URL }}{{ image.image.url }}" />

您还可以像这样向模型添加一个方法来跳过 MEDIA_ROOT 部分:

from django.conf import settings

class Image(...):

    ...

    def get_absolute_url(self):
        return settings.MEDIA_URL+"%s" % self.image.url

我也会像这样使用 upload_to 来保持理智:

models.ImageField(upload_to="appname/classname/fieldname")

试试这些设置:

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',
)
于 2012-04-13T13:32:30.343 回答
1

对于 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 }}">
于 2018-11-12T00:34:00.730 回答
0

您必须使包含上传图像的文件夹“可通过网络访问”,即要么使用 Django 从文件夹中提供静态文件,要么为此使用专用的网络服务器。

在您的模板代码中,您必须使用正确的MEDIA_URL值。

于 2012-04-13T13:30:00.063 回答