2

我在显示从管理面板上传的图像时遇到问题。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. 所以我猜所有路由/模板都可以,模型有问题。

4

3 回答 3

2

以上解决方案完全可以。我的问题是配置不正确的以 JSON 编写并加载到数据库中的装置。我认为在您将articles目录作为upload_tokwarg 传递时,它将被动态加载。不是。它仅在保存图像期间使用,在从数据库加载图像期间被忽略。因此,如果我有

"image":"slide.jpg"

我将其更改为:

"image":"articles/slide.jpg"

它奏效了。事实上,它一直有效,但我错过了 django 官方文档中的注释。

于 2013-03-21T12:37:07.833 回答
2

view.py中:

from django.shortcuts import render_to_response, RequestContext
def slider(request):
    articles = Article.objects.order_by('-created_at')[:5]
    return render_to_response('articles/slider.html', locals(), context_instance = RequestContext(request)

slider.html 中

{% for article in articles %}
    <img src="{{ MEDIA_URL }}{{ article.image.url }}" alt="" />
{% endfor %}

urls.py中:

from django.conf import settings
urlpatterns += patterns('',
    (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)

尝试使用上面给出的代码。

于 2013-03-21T08:42:58.603 回答
1

您是否尝试使用上传方法:

def upload_path(self, filename):
    return 'media/articles/%s' % filename

class Article(models.Model):
    ...
    image = models.ImageField(upload_to=upload_path, null=True, blank=True)
    ...
于 2013-03-21T08:42:40.233 回答