Django MEDIA_URL not working in template - python

I've read various answers on how to do this, but still can't seem to get it working.
settings.py
MEDIA_ROOT = 'c:/jaskaran/dropbox/edmhunters/hunt/media/'
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.media",
)
I have a 'media/img/' folder in my Django app and a 'static'folder as well.
view.py
def top100(request):
top_100_list = DJ.objects.exclude(rank__isnull=True).order_by('rank')
context = {'top_100_list': top_100_list}
return render_to_response('hunt/top100.html', context_instance=RequestContext(request, context))
urls.py
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is how i'm accessing the image in the Django template <img src="{{ MEDIA_URL }}{{ dj.img }}">
The image url doesn't add the MEDIA_URL to the image link.
What's missing in this code?

Sorry, noob mistake. I was using the <img src="{{ MEDIA_URL }}{{ dj.img }}"> in the wrong HTML file.

Your call to render_to_response looks like the issue, here.
return render_to_response('hunt/top100.html', context_instance=RequestContext(request, context))
should instead be:
return render_to_response('hunt/top100.html', context, context_instance=RequestContext(request))

Writing it the django way in the template by appending url to the model field name i.e.
<img src="{{ dj.img.url }}">
Also works and even more cleaner code compared to:
<img src="{{ MEDIA_URL }}{{ dj.img }}">

Related

Static image url is returned without MEDIA_URL

i followed this tutorial about displaying profile pictures on website, i did everything correctly (i hope so) but instead of returning example.com/media/posters/pic1.jpg it returns example.com/pictures/pic1.jpg (real example)
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
views.py
def index(request):
movies = {'movies' : movie.objects.all()}
return render(request, 'index.html', movies)
models.py
class movie(models.Model):
poster = models.ImageField(upload_to='posters')
and html
{% for a in movies %}
<img src="{{ a.poster }}" alt="">
{% endfor %}
i added + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to urls.py file
also, i had to use a.poster instead of poster.image.url, it just returned unknow, different django version i assume
You need {% get_media_prefix %}.

I can't see ImageField's photos in DJango's view [Solve]

something fail in my Django project, because the images that I load in the imagefields don't show in the view.
https://www.dropbox.com/sh/fvx6sfmxgm08xo6/AABVR-AQGeF52pCxlzVaLuDaa?dl=0
The crab's photo it's load with "static", but the second, that it's imagefield's photo.
enter image description here
Model:
class foto(models.Model):
nombre=models.CharField(max_length=50)
imagen=models.ImageField(upload_to='fotos/')
def __str__(self):
return self.nombre
View:
def general(request):
lista=foto.objects.all()
context={'material':lista}
return render(request,'indice.html',context)
settings:
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
'/media/fotos/',
)
html:
{% load staticfiles %}
<html>
<head>
<title>Album de fotos</title>
</head>
<body>
<img src="{% static 'cangrejo.jpg' %}" />
{% if material %}
{% for a in material %}
<li>{{a.nombre}}: {{a.imagen}}</li>
<img src="{{a.imagen}}" />
{% endfor %}
{% else %}
<p>No hay fotos</p>
{% endif %}
</body>
</html>
Admin's URLS:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('colecion.urls')),
]
View's URLS:
from django.conf.urls import url, include
from colecion import views
urlpatterns =[
url(r'^$',views.general),
]
Edit: I already solve the problem!
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'ciencia/static')
models.py
foto=models.ImageField()
html
<img src="{% static alfa.foto %}" />
From the docs:
MEDIA_URL - "Absolute filesystem path to the directory that will hold user-uploaded files."
MEDIA_ROOT - "URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments."
Your current config's MEDIA_URL doesn't look right. It should be a URL, you have it set to a filesystem path. Try something like
MEDIA_URL = '/media/'
Add this to urls.py
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Change {{a.imagen}} to {{a.imagen.url}}

Django template doesn't display ImageField

I have a model where there is a ImageField but in the template doesn't appears. The upload of the image is OK (in media_root/one/image.jpg)
Settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media_root")
Urls.py
(...)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
Models.py
class myModel1(models.Model):
__(...)
__image = models.ImageField(upload_to='one', default="")
__(...)
And on my template, I make this:
<img src="{{ myModel1.image.url }}" alt="{{ myModel1.name }} image" />
And on the HTML is like:
(...)**src="/media/one/photo_p33Mo8a.jpg"**(...)
But the image is not displayed
error 404 not found:
GET http://localhost:8000/media/one/photo_p33Mo8a.jpg 404 (NOT FOUND)
Can someone help me?
PD: Sorry, my first time writing on stackOverFlow.
Have to comment that in the media_root/one/ there appears the image, but the folder /media/ is still empty.
FOLDER STRUCTURE:
Proyect:
___app_folder
________media
________models.py....
___media_root
________one
____________image.jpg
___mainFolder(settings,urls..)
___static_root(...)
Try in your tremplate:
<img src="{{ MEDIA_URL }}{{ myModel1.image }}" alt="{{ myModel1.name }} image" />
*EDIT
It seems you have to add in your urls.py file:
from django.conf import settings
from django.views.static import serve
# ... the rest of your URLconf goes here ...
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT,
}),
]
Edit2
Your ROOT_MEDIA path should be:
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_root")

Django not show images

Pls tell me. Why ../static/image.jpg show images, and ../media/image.jpg now show
Need write url? Need change Setting? i dont fiend answer in documentation.
pls help.
2 night search answer.
Need upload from admin-panel photo and show in templates.
<img src="{{ tovar.product_img.url }}">
To display image you need load the static files in your template before referencing them. This is how you should display a picture in your template:
{% load staticfiles %}
<img src="{% static 'image.jpg' %}">
This image needs to be stored in your static folder. ../YourApp/YourApp/static/image.jpg is where I keep my static folder. Obviously it would be better to structure it further with images folder inside the static folder etc..
In your settings file you need the following lines:
# Static asset configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
This should do the trick for you.
In settings.py
MEDIA_ROOT = '/path/to/yourmediafolder/'
MEDIA_URL = '/media/' # whatever but it should same in `urls.py`
In urls.py
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
Then in template
<img src="{{ MEDIA_URL }}images/imagename.jpg"/>
Note: Here image should be as '/path/to/yourmediafolder/images/imagename.jpg'
Complete example:
I have an image test.jpg as '/home/me/test.jpg
MEDIA_ROOT = '/home/' # or /home/me/ but change url in image src
MEDIA_URL = '/media/'
#urls.py same as above
In template
<img src="{{ MEDIA_URL }}me/test.jpg"/> # or <img src="{{ MEDIA_URL }}test.jpg"/> as or condition above in MEDIA_ROOT.
Note that {{ MEDIA_URL }}me , no / between them because MEDIA_URL='/media/
You can test by:
http://domain.com/media/me/test.jpg # or http://domain.com/media/test.jpg as OR condition in MEDIA_ROOT
in local:
http://localhost:8000/media/me/test.jpg #in locally
This works (in the html img tag):
src="(left squiggly, percent) static poc.image.name (percent, right squiggly):
...and thanks to whoever pointed out that ImageField has a name in addition to a (useless) path and (useless) url e.g.:
>>> from nutr.models import *
>>> poc=POC.objects.get(pk=87)
>>> poc.name
'Edgar'
In Django==2.0.2 use {% get_media_prefix %}
From the docs

Media files fail Django

I have a common problem with medias. I have a model which save an image in the media folder :
class Article(models.Model):
titre = models.CharField(max_length=100)
auteur = models.CharField(max_length=42)
contenu = models.TextField(null=True)
date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date")
photo = models.ImageField(upload_to="blog/media/upload/photos/", default="default.jpg")
But in my template when I try to get my picture by this way :
<img class="photo" src="{{ media_url }} {{ article.photo }}">
the {{ media_url }} is blank !
In my settings.py file I tried different configuration (found on this website), actually this is :
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
#MEDIA_URL = 'http://localhost:8000/blog/media/'
#MEDIA_ROOT = '/blog/media/'
MEDIA_ROOT = '/home/remi/perso/django/projets/SiteBlog/blog/media/'
ROOT_PATH = os.path.dirname(__file__)
STATICFILES_DIRS = (
os.path.join(ROOT_PATH, 'static'),
)
It works well for static files but not at all for media files.
I also tried to add in urls.py this :
# urlpatterns += patterns('',
# (r'^media/(?P<path>.*)$', 'django.views.static.serve', {
# 'document_root' : settings.MEDIA_ROOT}))
But with ths I get an "Syntax error".
Sorry to post for a common problem like that but I didn't find any working solution for me !
Thanks !
RĂ©mi.
Fitst change {{ media_url }} with {{ MEDIA_URL }} in your template.
<img class="photo" src="{{ MEDIA_URL }} {{ article.photo }}">
And change urls.py like this:
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))

Categories

Resources