I uploaded images with admin, but cannot render them in the template. What am I missing?
Settings.py
STATIC_URL = '/static/'
STATIC_DIRS = { os.path.join(BASE_DIR, "static"),
}
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Models.py
class Function(models.Model):
name = models.CharField(max_length=50)
fimage = models.ImageField(upload_to="images")
def __unicode__(self):
return "name{},id{}".format(self.name, self.id)
HTML
{% for function in functions %}
<a href="function_page/{{function.id}}">
<img id=function_menu_pic src="{{MEDIA_URL}}{{function.fimage.url}}"></a>
{% endfor %}
Views.py
def main(request):
context = {
"functions": Function.objects.all()
}
return render (request, 'project/main.html', context)
Urls.py
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
When I upload the files they are going to a media file that is at the same level as manage.py. I'm not sure how the routing works from there.
I'm getting this message for all the images:
Not Found: /media/images/lpo.png
[02/Feb/2018 09:54:01] "GET /media/images/1_ssOAG27.png HTTP/1.1" 404 2748
答案 0 :(得分:0)
Remove {{MEDIA_URL}}
in img src and put quotes"
in id..
<img id="function_menu_pic" src="{{function.fimage.url}}">
答案 1 :(得分:0)
It took me a long time to fix this, so I want to share how I fixed it:
I followed Astik's advice above and made changes to the template.
I reset my absolute path. This blog helped immensely. Timothey Mahony blog
`ENV_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(ENV_PATH, 'media/')`
I hope this helps if you ever get stuck in the same place I was!
https://timmyomahony.com/blog/static-vs-media-and-root-vs-path-in-django/