4

我可以通过 Django admin 在我的一个模型中成功保存文件,但之后无法打开该文件。这是我的模型:

class Answer (models.Model):
    answer = models.CharField(max_length=1000)
    attach_file = models.FileField(upload_to='Attachments', blank=True)

我没有触及设置文件,据我了解,它应该使用默认值:

MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''

我在 admin.py 中注册了模型,并且能够浏览文件并保存它。尝试打开该文件时,我得到:

Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/businessui/answer/1/Attachments/outlook.png/
answer object with primary key u'1/Attachments/outlook.png' does not exist.

有人能指出我在这里缺少什么,以便能够在我的开发机器上本地打开保存的文件吗?

4

2 回答 2

5

尝试像这样设置您的 settings.py:

import os
PROJECT_ROOT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))

MEDIA_ROOT = os.path.join(PROJECT_ROOT_PATH, 'media/')
MEDIA_URL = '/media/'

因此,尝试将您的文件放入:

http://127.0.0.1:8000/media/Attachments/outlook.png
于 2012-10-11T14:51:06.050 回答
2

参考@Sawwy 对@RicardoCarmo 的回答的评论。我发布作为格式的答案。

这是我在主 url conf 中使用的内容:

if getattr(settings, 'DEBUG', False) or getattr(settings, 'DEBUG_MEDIA', False):
    media_url = getattr(settings, 'MEDIA_URL', '/media/').lstrip('/')
    urlpatterns = patterns('',
        url(r'^%s(?P<path>.*)$' % (media_url,), 'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT
        }),
    ) + urlpatterns

Note that in a production environment, your media files should be served up by the web server and those requests should not reach Django. That is why it's qualified with if DEBUG or DEBUG_MEDIA.

于 2012-10-11T16:59:53.083 回答