无法显示上传的图片django

时间:2015-08-29 13:07:55

标签: python django python-3.x django-models django-forms

为什么我无法使用以下设置正确显示上传的图像。 在查看页面源时,URL正确显示(我认为)。图像只是破碎的图像缩略图。源中的网址显示为/media/uploads/group_images/my_image_name

如果相关,图片是从管理员上传的,但我也希望能够在其他地方上传(即 - 在渲染模板中上传表单)

在settings.py

....
MEDIA_URL = "/media/"
MEDIAFILES_DIRS = []
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

在models.py

class BlogGroup(models.Model):

    title = BleachField()
    image = models.ImageField(upload_to="uploads/group_images", default="uploads/group_images/none/none.jpg")
    created = models.DateTimeField(default = datetime.now)

    def __str__(self):

        return self.title 

在forms.py

class BlogGroupForm(forms.ModelForm):


    def __init__(self, *args, **kwargs):

        super(BlogGroupForm, self).__init__(*args, **kwargs)
        self.fields["title"].requried = True
        self.fields["image"].required = True
        self.fields["title"].widget = forms.TextInput()

    class Meta:
        model = BlogGroup
        fields = ["title", "image"]

urls.py

urlpatterns = patterns('blog.views',
 (r'^admin/', include(admin.site.urls)),
  .....,
 (r'^ckeditor/', include('ckeditor.urls')),
 (r"", "main"),
 ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

查看

def main(request):

    groups = BlogGroup.objects.all().order_by("created")
    context = {'groups':groups, 'user':request.user}
    return render(request, "list.html", context)

模板

{% for group in groups %}
<div class = "row">
    <div class = "col-xs-12">
        {{ group.title }}
    </div>
    <div class = "col-xs-12">
        <img src = "{{ group.image.url }}" alt = ""/>
    </div>
</div>
{% endfor %}

2 个答案:

答案 0 :(得分:2)

问题出在您的网址调度程序中。 当django向调度员发送url时,它会从上到下逐个丢弃你的url,如果有正则表达式匹配则停止。

""中的您的网址(r"", "main"),与所有字符串匹配。 您需要将其替换为(r"^$", "main"),以匹配空字符串。

更多信息:

答案 1 :(得分:0)

像这样改变你的url.py:

    urlpatterns = patterns('blog.views',
 (r'^admin/', include(admin.site.urls)),
  .....,
 (r'^ckeditor/', include('ckeditor.urls')),
 (r"", "main"),
 ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)