我在显示从管理面板上传的图像时遇到问题。Django呈现错误的路径,可能是由于我在某处的配置错误......
这是我的模型定义:
class Article(models.Model):
"""News article, displayed on homepage to attract users"""
class Meta:
db_table = 'article'
title = models.CharField(max_length=64)
headline = models.CharField(max_length=255)
content = HTMLField()
image = models.ImageField(upload_to = 'articles/', null=True, blank=True)
active = models.BooleanField()
created_at = models.DateTimeField()
def __unicode__(self):
return self.title
这是网址配置:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# some stuff
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
设置.py:
PROJECT_DIR = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(PROJECT_DIR, "media")
MEDIA_URL = '/media/'
风景:
def slider(request):
context = Context ({ 'articles': Article.objects.order_by('-created_at')[:5] })
return render(request, 'articles/slider.html', context)
和模板:
{% for article in articles %}
<img src="{{ article.image.url }}" alt="" />
我希望 django 渲染http://127.0.0.1:8000/media/articles/slide-02.jpg
,但现在它渲染http://127.0.0.1:8000/media/slide-02.jpg
. 我已经upload_to=articles/
在模型类中定义了。那么为什么该article.image.url
属性返回一个没有这个重要目录的路径呢?
编辑:我的模型有问题。它无法识别upload_to目录:
$ ./manage.py shell
Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from articles.models import Article
>>> Article.objects.all()
[<Article: Blackened Recordings Launches>, <Article: The Rockin' Return of Deep Purple>, <Article: See Emily Day 20th April>, <Article: Celebration Day Premieres In Four Countries Announced>, <Article: Waging heavy innovation>, <Article: Rush to play festival D'Ete, Quebec City>]
>>> Article.objects.all().get(pk=1)
<Article: Blackened Recordings Launches>
>>> Article.objects.all().get(pk=1).image
<ImageFieldFile: slide-03.jpg>
>>> Article.objects.all().get(pk=1).image.path
u'/var/www/django/djninja/djninja/media/slide-03.jpg'
>>> Article.objects.all().get(pk=1).image.url
'/media/slide-03.jpg'
同样,它应该media/articles/slide-03.jpg
代替media/slide-03.jpg
. 所以我猜所有路由/模板都可以,模型有问题。