我有一个非常简单的django网站,但我无法获取我在管理面板中上传的图片来显示。
我的settings.py
有以下常量:
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/jeroen/programming/python/django/sitename/media'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://127.0.0.1:8000/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
我的urls.py
看起来像这样:
from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^sitename/', include('sitename.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
# http://docs.djangoproject.com/en/dev/howto/static-files/
# This method is inefficient and insecure.
# Do not use this in a production setting.
# Use this only for development.
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
我的models.py
看起来像这样:
from django.db import models
class Truitje(models.Model):
titel = models.CharField(max_length=50)
beschrijving = models.TextField(max_length=500)
foto = models.ImageField(upload_to='truitjes')
def __unicode__(self):
return self.titel
我可以在管理界面中成功上传图片,并将其存储在/home/jeroen/programming/python/django/sitename/media/truitjes
中。但是当我以http://127.0.0.1:8000/media/truitjes/DSC00068.JPG
为例时,我收到了一个错误:Page not found: /media/truitjes/DSC00068.JPG
。 http://127.0.0.1:8000/media/truitjes
和“http://127.0.0.1:8000/media/ gives
权限相同:/ media /`。
答案 0 :(得分:11)
将您的媒体或管理网址/前缀更改为其他内容。
它们不能具有相同的值。如果他们这样做,ADMIN_MEDIA_PREFIX
优先。这意味着如果您尝试访问http://127.0.0.1:8000/media
,则表示您正在尝试访问管理媒体文件夹。
更改ADMIN_MEDIA_PREFIX
:
ADMIN_MEDIA_PREFIX = '/admin-media/'
或更改MEDIA_ROOT
:
# in settings.py
MEDIA_ROOT = '/home/jeroen/programming/python/django/ninikske/static'
MEDIA_URL = 'http://127.0.0.1:8000/static/'
# and in url.conf
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
答案 1 :(得分:5)
在Django 1.3中如果您只是想在开发过程中尝试在视图中显示图像,请按照以下步骤操作:
在你的app / urls.py中:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
#..rest of url.py config...
urlpatterns += staticfiles_urlpatterns()
在您的模板中,无论您希望图片显示在哪里,都可以使用此模板标记:
<img src="{{ STATIC_URL }}pic.png" />
在此处查看在开发中提供静态文件:https://docs.djangoproject.com/en/1.3/howto/static-files/#staticfiles-in-templates