从文件系统提供上传文件的问题

时间:2013-09-22 10:29:49

标签: django

我使用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) 

我做错了什么?

1 个答案:

答案 0 :(得分: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包含的全部产品现在看起来像这样:

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/'

现在,图片在上传后正确显示。感谢您的关注和答案。