Images from ImageField in Django don't load in template

后端 未结 7 1419
温柔的废话
温柔的废话 2020-12-08 15:58

I\'m building a gallery using Django(1.5.1) on my local machine. In my Album model I have a ImageField. There is a view to show all images of an album. It works

7条回答
  •  广开言路
    2020-12-08 16:31

    I took a little from each of the answers above. I was having the same problem as you. I was getting returns that were being directed from the current /blog/post/(media_url)/image.jpg

    In my admin portal I could view it easily and edit it. But on my post.html I was having problems until I added the {{ MEDIA_URL }} --

    That is all that I was missing.

    I posted my entire section below so that other people could read it and see what they are missing.

    post.html:
    
        
    
    models.py:
    
        from django.core.files.storage import FileSystemStorage
    
        upload_location =
        FileSystemStorage(location='/home/pi/djcode/xpcpro/xpcpro/images')
    
        class Blog(models.Model):
            title = models.CharField(max_length=255)
            author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
            date = models.DateTimeField(auto_now=False, auto_now_add=True)
            body = models.TextField()
            image = models.ImageField(
                storage=upload_location, null=True,
                blank=True, width_field="width_field",
                height_field="height_field",)
            height_field = models.IntegerField(default=0)
            width_field = models.IntegerField(default=0)
    
    urls.py:
    
        from django.conf.urls.static import static
        from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    
        urlpatterns += staticfiles_urlpatterns()
        urlpatterns += static(settings.MEDIA_URL,
        document_root=settings.MEDIA_ROOT)
    
    settings.py:
    
        MEDIA_ROOT = "/home/pi/djcode/xpcpro/xpcpro/images/"
        MEDIA_URL = "/images/"
    

提交回复
热议问题