1

我使用 Django 1.5.4 制作了一个项目,现在在本地上传文件时遇到了问题。我的 urls.py 现在看起来像这样:

urlpatterns = patterns('',
    url(r'^$', views.home),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_ROOT, document_root='')

在 models.py 中有一个 Product 类的 ImageField:

photo = models.ImageField(upload_to=MEDIA_ROOT)

以及显示它的方法:

def display_photo(self):
    return '<img src="%s" />' % (self.photo)

display_photo.short_description = 'Photo of a product'
display_photo.allow_tags = True

最后,settings.py 中的 MEDIA_ROOT:

MEDIA_ROOT = '/home/nervosa/DjangoProjects/Sit_test/uploads/'

仍然萤火虫显示错误:

GET http://127.0.0.1:8000/home/nervosa/DjangoProjects/Sit_test/uploads/cover.jpg 404 (NOT FOUND) 

我做错了什么?

4

1 回答 1

0

解决了。我只需要修改 urls.py:

urlpatterns = patterns('',
    url(r'^$', views.home),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT,
        }),
    )

models.py 包含的整个类 Product 现在看起来像这样:

class Product(models.Model):
    title = models.CharField(max_length=50)
    height = models.FloatField(max_length=10)
    weight = models.FloatField(max_length=10)
    color = models.CharField(max_length=7)
    photo = models.ImageField(upload_to='products_photo/')
    thumbnail = ThumbnailerImageField(default='', upload_to='products_photo_thumbnails')

    def __unicode__(self):
        return self.title

    def display_photo(self):
        return '<img src="%s" />' % (self.photo.url)

    display_photo.short_description = 'Photo of a product'
    display_photo.allow_tags = True

很抱歉没有提供我的 ModelAdmin - 这里是:

class ProductAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Title of a product',         {'fields':['title']}),
        ('Parameters of a product',    {'fields':['height', 'weight', 'color']}),
        ('Upload a photo',                      {'fields':['photo']}),
        ('Photo',             {'fields':['display_photo']}),
    ]
    list_display = ['title', 'height', 'weight', 'color']
    readonly_fields = ('display_photo',)

admin.site.register(Product, ProductAdmin)

最后 - MEDIA_ROOT 和 MEDIA_URL - 在我的情况下,它们应该是:

MEDIA_ROOT = '/home/nervosa/DjangoProjects/Sit_test/'
MEDIA_URL = '/uploads/'

现在图像在上传后正确显示。感谢关注和解答。

于 2013-09-22T19:30:18.023 回答