django MEDIA_ROOT and MEDIA_URL TEMPLATES - python

the model looks like
class Cars(models.Model):
name = models.CharFidle(max_length=255)
price = models.DecimalField(max_digits=5,decimal_places=2)
photo = models.ImageField(upload_to='images/cars')
def __unicode__(self):
return self.name
the settings
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
but when I use the it in the templates like this
{% for car in cars %}
<li>{{ car.name }}</li>
<li>{{ car.price }}</li>
<a>{{ car.photo }}</a>
<img src="{{ car.photo.url }}"/>
{% endfor %}
I can't get the image, what's the matter?
It would be wonderful anyone help me

There are a few things that could be going on here:
You're running a non-development web server that hasn't been setup to serve static media. The solution here will vary depending on what web server you're running.
You're running the development web server and haven't setup static serving. For this, I'd add the following to your root urls.py file:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
There's a permissions issue in your MEDIA_ROOT directory. In this case, I'd make sure your MEDIA_ROOT directory is readable by your web server.

From your settings.py I assume you have made a media folder in your base directory. If u had then you are going right. I assume the problem is in your template.
Try this:
<img src="/static/{{car.photo}}" width="100" height="100" />
Dont forget to include {% load staticfiles %} at the top of the template after extending the base.. You are ready to go...

urlpatterns = [
# ... the rest of your URLconf goes here ..
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
add this to my root urls.py, and remeber in the root urls.py

Related

How to access the image in django template? [duplicate]

I'm new in Django. I read a lot on documentation and on this site about my question. But I really can not understand what I should do to make this. Can someone show me with all steps please?
model.py:
class Post(models.Model):
title=models.CharField(max_lengt=50)
img=models.ImageField(upload_to = 'images')
template:
{% for post in posts %}
<h1> {{post.title}} </h1>
<img src="{{post.img}}">
{% endfor %}
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
If I access the admin page, how can I upload the image? In template I can't see image!
Sorry for my bad English. Help me please
In template, use:
{% for post in posts %}
<h1> {{post.title}} </h1>
<img src="{{ post.img.url }}">
{% endfor %}
You have to add {{ post.img.url }}.
Also, make sure that in urls.py, you have:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
It will Work.

"Could not load the image" from Django's media folder

I'm trying to display an image from a database (SQLite, Django2.7). These images are stored in root/media/pictures.
models.py
class News(models.Model):
news_id = models.AutoField(primary_key=True, editable=False)
news_img = models.FileField(upload_to="pictures/",validators=[FileExtensionValidator(allowed_extensions=['svg'])] )
urls.py
urlpatterns = [...]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I've try to insert the path in the var in the following methods:
template.html
{% for news_f in news_f%}
<div>
<img src="{{ media }}{{news_f.news_img}}">
</div>
{% endblock %}
and
{% for news_f in news_f%}
<div>
<img src="{{news_f.news_img.url}}">
</div>
{% endblock %}
When I inspect the element in the browser, I get the correct path to the file.
<img src="/media/pictures/file.svg">
But it isn't displayed in the HTML:
Could not load the image
That happens because django doesn't serve static files. Usually you use django along with some webserver like nginx and those servers are more reliable serving files.
Please check out django docs https://docs.djangoproject.com/en/2.2/howto/static-files/deployment/
Your configuration for media files is right, the problem is that Django doesn't serve SVG files with the right mime type by default, this answer explains how to make it work.

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 %}.

Django - Unable to display an image from folder within media folder

I am trying to load an image from a folder within 'media' folder (media/tshrirts) onto template using django. Below is my settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
MEDIA_URL = '/media/'
#MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = 'media'
**I tried both the roots none of them work.
Below is my models.py
from django.db import models
# Create your models here.
class tshirts(models.Model):
brand=models.CharField(max_length=50)
name=models.CharField(max_length=100)
price=models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='tshirts/')
def __str__(self):
return self.name
this is part of the tshirts.html Why image.url is none??
<div class='tshirts'>
{% for eachtshirt in alltshirts %}
<div class='tshirt'>
{{eachtshirt.brand}}
<p>{{eachtshirt.name}}</p>
<p>{{eachtshirt.price}}</p>
<img src="{{eachshirt.image.url}}"/>
{% if eachshirt.image.url == None %}
<p>{{"Image Not Found"}}</p>
{% endif %}
</div>
{% endfor %}
</div>
finally, urls.py
urlpatterns = [
.
.
.
url(r'^tshirts/',include('tshirts.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
After I uploaded the image as an admin and clicked the link, the image was properly displayed.
http://127.0.0.1:8000/media/tshirts/t-shirt2.jpg - the image was displayed here.
How can I fix this, please let me know thanks!!!
Screenshot for the page
The root of your media, should include the BASE_DIR, like the following:
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
You have a typo in your template, you'are accessing {{eachshirt.image.url}} without t. the correct is
{{eachtshirt.image.url}} <!-- with t : each tshirt -->

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}}

Categories

Resources