I need to show images in templates. The images are fetched from models. My models.py reside in an app named services:
class Car_model(models.Model):
name = models.CharField (max_length = 25, blank=False)
...
category = models.ForeignKey (Category, on_delete=models.CASCADE)
photo = models.ImageField (upload_to ='static/images/models')
I have added these lines in my settings.py:
STATIC_ROOT = os.path.join(BASE_DIR, 'media') # i added it later
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
I have also added this line in my project_name's urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I am trying to get the images in my templates through this code:
{% load static %}
{% for c in ca %}
<p><strong>{{ c.car_no }}</strong>--<em>{{ c.car_model }}</em>--{{ c.garage }}</p>
<img src="{{ c.car_model.photo.url }}" height="200" />
<form action="{%url 'booking' c.id c.garage.id %}" method="POST">
{% csrf_token %}
<input type="submit" name="the_selected_car" value="Select this car">
</form>
{% endfor %}
But whatever I try photos aren't showing. I tried by placing this:
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) in my services app's urls.py but that didn't help.
You forget to add MEDIA_ROOT and MEDIA_URL in settings.py and load media urls in urls.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
and in urls.py
urlpatterns = [
........
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your could Refactor your upload_to in photo field
1. If you want to upload images in static director
photo = models.ImageField (upload_to ='static/images/models')
And set static folder in MEDIA_ROOT as below
MEDIA_ROOT = os.path.join(BASE_DIR, 'static')
2. If you want to upload images in media director
Since your are storing uploaded images I would suggest store in defferent director like media , uploads
Change your field as below.
photo = models.ImageField (upload_to ='media/images/car_model')
Now All your images related to Car_Model will be saved inside media/images/car_model
And set media folder in MEDIA_ROOT as below MEDIA_ROOT as below
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
you didn't include MEDIA Urls in your urls.py
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Related
#urs.py
urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#setting.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = 'media/'
#model
images = models.ImageField(upload_to='BonusVilla/image/', blank=True)
#tempalte
{%for i in images%}
<img src="{{ i.images.url }}" />
{%endfor%}
#the browser it renders this
<img src="/media/BonusVilla/image/apple_3H8ByYb.jpg">
I can't seem to figure out why my media images are not showing up in my template. I've read many articles but couldn't resolve. I have a model that has a relation with another model that has an imagefield
class Ad(models.Model):
company = models.ForeignKey(Company, related_name='ads', on_delete=models.CASCADE)
title = models.TextField(max_length=240)
text_description = models.TextField(max_length=2500)
created_at = models.DateTimeField(auto_now=True)
slug = models.SlugField(unique=False)
The imagefield from the Company model gets uploaded to a folder called /logos/ that is under /media/
class Company(models.Model):
logo = models.ImageField(blank=True, upload_to='logos/')
And these are the settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
and urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.HomePage.as_view(), name='home'),
]
if settings.DEBUG:
urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and views.py:
class SingleAd(DetailView):
model = Ad
Then im trying to loop through images and add to the template:
{% load static %}
{% for ad in object_list %}
<div>
{% if ad.company.logo %}
<img src="{{ ad.company.logo.url }}" height="100"/>
{% endif %}
</div>
{% endfor %}
The result is a blank image (although the concrete object has an image) and the HTML renders such a tag
<img src="/media/logos/security-265130_1920_IBWqpIq.jpg" height="100">
The image does exist and with the correct path and name as shown in rendered img tag. What am I doing wrong here? Staticfiles images like the website brand and background images are being rendered as expected
I changed
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.HomePage.as_view(), name='home'),
]
if settings.DEBUG:
urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
to:
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.HomePage.as_view(), name='home'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and problem was fixed
is there something wrong with my code? i already run makemigrations and migrate, and i can see the picture i saved on the admin site, but why when i try to call this picture on my html i received this error?
this is my html
{% for perfume in s %}
<img src="{{perfume.image.url}}" width="192px" height="192px" class="class">
{% endfor %}
my views.py
s = Perfume.objects.all()
....
my models.py
class Perfume(models.Model):
image = models.ImageField(upload_to='image',null=True, blank=True)
....
my settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
LOGIN_REDIRECT_URL = '/'
import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
def get_success_url(self, request, user):
return (get_success_url)
my urls.py
urlpatterns = [
....
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your ImageField declared blank=True, null=True so image can be empty. You need to check if image has uploaded in your html.
{% for perfume in s %}
{% if perfume.image %}
<img src="{{ perfume.image.url }}">
{% endif %}
{% endfor %}
I have a problem when trying to display in a template a picture from my media file (for example a profil picture from an user). I have already looked at many topics, and everytime the answer is simply adding the line urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in the urls.py file. But I already have it and it still doesn't work. Here are the relevant part of my files :
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('actualites.urls')),
path('inscription/', include('inscription.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
views.py
def home(request):
return render(request, 'actualites/home.html', {'last_meals': Plat.objects.all()})
models.py
class Plat(models.Model):
titre = models.CharField(max_length = 100)
date = models.DateField(default=timezone.now, verbose_name="Date de préparation")
photo = models.ImageField(upload_to = "photos_plat/", blank = True)
class Meta:
verbose_name = "Plat"
ordering = ['date']
def __str__(self):
return self.titre
You can see that the pictures are recorded in the photos_plat directory, which is a subdirectory of the media directory.
the template :
{% extends "base.html" %}
{% block content %}
<h2>Bienvenue !</h2>
<p>
Voici la liste des plats disponibles :
</p>
{% for meal in last_meals %}
<div class="meal">
<h3>{{ meal.title }}</h3>
<img src="{{ meal.photo.url }}" height=512 width=512/>
<p>{{ meal.description|truncatewords_html:10 }}</p>
<p>Afficher le plat</p>
</div>
{% empty %}
<p>Aucun plat disponible.</p>
{% endfor %}
{% endblock %}
When I go the home page, I get the following error : ValueError at /
The 'photo' attribute has no file associated with it.
I have tried moving the pictures from the "photos_plat" directory directly to the media directory but that changes nothing.
I don't know what I did wrong, can someone help me please ?
Thanks in advance !
I am developing a django app were i am uploading images through the admin panel
i have implemented this in my other apps but i can seem to get what is wrong with my configurations as follows
settings.py
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'ntakibariapp.Member'
LOGOUT_REDIRECT_URL = 'ntakimbari:_login'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('ntakibariapp.urls')),
path('accounts/', include('django.contrib.auth.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, ducument_root=settings.MEDIA_ROOT)
models.py
class Community_work(models.Model):
where = models.CharField(max_length=80)
time = models.TimeField(blank=False)
date = models.DateField(blank=False)
image_of_area = models.ImageField(upload_to='photos',blank=True)
post_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.where
template/communtity_work.html
{% extends 'temp/base.html' %}
{% block title %}community works{% endblock %}
{% block body %}
<div class="container">
{% for work in works %}
<p>Picture of the area <img src="{{work.image_of_area.url}}"></p>
<p>Where: {{work.where}}</p>
<p>Time: {{work.time}}</p>
<p>Date: {{work.date}}</p>
{% endfor %}
</div>
{% endblock %}
in urls.py you have a misspell try use
document_root
instead of ducument_root
Also shouldn't the tag be <img src="{{community_work.image_of_area.url}}">?