My image path is working but Idk why it's not able to display it, any help is appreciated
models.py
class movies(models.Model):
Image = models.ImageField(blank=True, null=True)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = 'media'
home.html
{% for m in movies %}
<img src="{{ m.Image.url }}" width="200px", height="300px">
{% endfor %}
class movies(models.Model):
Image = models.ImageField(upload_to='images/', blank=True, null=True)
So the problem was with the Media root, my path was fine but Django wasn't able to get it somehow, so I ran this code to automate Django to find media root by itself
ENV_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(ENV_PATH, 'media/')
and made a debug condition in the urls.py to run the request if viewed under development or localhost
if settings.DEBUG is True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Related
I used Django Admin to upload an image and I am trying to get it to display in a template. The alt text is displayed but I keep getting a 404 error for the image and it does not display. When I uploaded the image the path that it pulls in the template media/images/mari-profile-pic.png is valid and contains the image I am trying to display.
models.py
from django.db import models
# Create your models here.
class Image(models.Model):
title = models.CharField(max_length=50)
image = models.ImageField(upload_to='images/')
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Image
# Create your views here.
def index(request):
imageModel = Image.objects.get(pk=1)
return render(
request,
"SocialLinks/index.html",
{
"profile_pic_title":imageModel.title,
"profile_pic":imageModel.image
}
)
index.html template
<div id="profile">
<img id="userPhoto" src="{% get_media_prefix %}{{ profile_pic }}" alt="{{ profile_pic_title }}">
</div>
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
I have tried removing and adding the {% get_media_prefix %} tag and the image still does not display.
settings.py:
MEDIA_URL = '/media/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
VENV_PATH = os.path.dirname(BASE_DIR)
STATIC_ROOT = os.path.join(VENV_PATH, 'static_root')
MEDIA_ROOT = os.path.join(VENV_PATH, 'media_root')
your.html:
{% load static %}
To make the imgaes works add .url to be like this: {{ i.img.url }}, and go to the urls.py of the app, and add the following:
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Call the templates and the statics from the (PROJECTNAME/settings.py) by add the following in the TEMPLATES 'DIRS':
'DIRS': [os.path.join(BASE_DIR, 'temp')],
I'm trying to built a CMS for the admin where he is able to change the images.
But so far it doesn't work and I can't find the error.
Here is the model and there is no default.png
models.py
class Media(models.Model):
image = models.ImageField(blank=True, null=True)
class Meta:
verbose_name_plural = "Photo"
def __str__(self):
return self.image.name
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
print(MEDIA_ROOT)
views.py
def gallery_view(request):
return render(request, 'web/gallery.html', context={"pic": Media.objects.first()})
Here is my template for the ImageField:
<img class="ui bordered image" src="{{ pic.image.url }}">
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('webpage/', include('webpage.urls')),
path('', include('web.urls')),
path(r'^', include('web.urls', namespace='web')),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Now when I print(MEDIA_ROOT) my terminal shows this:
'Not Found: /media/default.png'
"GET /media/default.png HTTP/1.1" 404 1808"
and
"POST /admin/web/media/add/ HTTP/1.1" 302 0"
"GET /admin/web/media/ HTTP/1.1" 200 1282"
Does anyone have a suggestion for me where the bug is?
Thanks in advance.
Double check if you have added paths for both Static and Media URL in settings.py.
For Static URL:
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
For Media URL:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
To access display your img:
<img class="border-radius-50 profile-img" src="{{ MEDIA_URL }}{{ pic.image.url }}" alt="...">
class Media(models.Model):
image = models.ImageField(blank=True, null=True)
Give a default value for you models
image = models.Imagefield(blank =True, null=True, default ="add photo")
Makemigrations and migrate after adding default.
Not so sure for views
def gallery_view(request):
if(request.method=='POST'):
= request.POST['media']
value = 'Media : %s (media)
return render(request, 'web/gallery.html', context={"pic": Media.objects.first()})
I'm actually new to django and I found a problem when loading my images, I did the settings like the docs said and it saves my images to the right folder. Just the loading part does not work as I want it to.
# the settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# the Model
class Legend(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=300)
creator = models.ForeignKey(User, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now=True)
published = models.DateTimeField(null=True, blank=True)
available = models.BooleanField(default=False)
image = models.ImageField(upload_to='gallery', blank=True, null=True)
# the template where i use the img field
{% for instance in object_list %}
<img style="width: 245px; height: 247px;" src="{{ instance.image.url }}" alt="legend image"">
{% endfor %}
the upload is working as expected. Saves all images to the media folder (which is on the applevel)
so: media/gallery/name.jpg.
running the server doesnt show the image but the source seems fine:
http://127.0.0.1:8000/media/gallery/gto.jpg
There seems to be a problem with serving files locally when debugging, but all i could find were for older django versions. Iam using django --version 2.2.
I appreciaty any help
When you are running django under DEBUG = True, you should also add media urls:
Add this to end of your main urls.py:
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# and this one to serve static files:
#urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I have images I uploaded through django admin, but they are not displaying. The weird thing is that I have another project with the EXACT same code and it works. object.image.url outputs /media/media/image.jpg as does my other project. But this project does not show the image. if I put an image from my static folder or if I hardcode an image, it works fine. The problem is only when I try an image uploaded from the admin it does not work. Am I missing something in my settings.py file? or anywhere?
Models.py:
from django.db import models
# Create your models here.
class Connect(models.Model):
title = models.CharField(max_length=70)
short_description = models.TextField(null=True, blank=True)
description = models.TextField()
image = models.ImageField(upload_to='media', blank=True, null=True)
def __str__(self):
return self.title
views.py:
def index(request):
about = About.objects.all()
staff = Staffmembers.objects.all()
ministries = Ministries.objects.all()
connect = Connect.objects.all()
context = {
'template': 'home',
'connect': connect,
'about': about,
'staff': staff,
'ministries': ministries,
}
return render(request,'home/index.html', context)
template(index.html):
<div class="connect-wrapper row">
<h1 class="title connect-title">Connect</h1>
{% for object in connect %}
<div class="home-div connect-div col-md-4">
<h4>{{ object.title }}</h4>
<p>{{ object.short_description }}</p>
{% if object.image %}
<img class="connect-image-home" src="{{object.image.url}}" alt="connect">
<p>{{object.image.url}}</p> //sanity check
{% endif %}
</div>
{% endfor %}
</div>
settings.py:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
urls.py:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('home.urls'), name="home"),
]
I believe you need to add the media urls to your urls.py. Something like:
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('home.urls'), name="home"),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
On production environment Django does not load the media root automatically so that we can we can overcome that issue by adding following after url patterns:
urlpatterns = [
''''
your urls
''''
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
If you are using more than one app and including app urls on main app url, just add this on main project url.
Settings.py
STATIC_URL = '/static/'
MEDIA_ROOT='/home/akanksha/bookepdia/media/'
MEDIA_URL = '/media/'
TEMPLATE_DIRS = ('/home/akanksha/bookepdia/templates',)
Model.py
class Image(models.Model):
title = models.CharField(max_length=255)
photo = models.ImageField(upload_to='/home/akanksha/bookepdia/media/images/')
Url.py
urlpatterns = patterns('',
url(r'^$', 'bookepdia.views.home', name='home'),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Views.py
def home(request):
photos = Image.objects.all()
return render_to_response('display.html', {'photos' : photos})
display.html
<html>
<h3>Images of books</h3>
<img src="/media/images/image_name" />
{% for p in photos %}
<img src="{{p.photo.url}}" />
{% endfor %}
</html>
Now,my problem is when I have added /media/images/image_name the image is displayed but when I use {{p.photo.url}} the image is displayed as broken icon.
I found out it is taking the path as /home/akanksha/bookepdia/media/images/image_name.
Now,I want to edit this for every url so that it works as /media/images/image_name.
You shouldn't give absolute path into upload_to in ImageField, it should be path relative to your MEDIA_ROOT.
upload_to attribute of ImageField is not absolute path, it is relative to MEDIA_ROOT setting.
In your case it should be like this:
photo = models.ImageField(upload_to='images')
See documentation: https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.FileField.upload_to
FileField.upload_to
A local filesystem path that will be appended to your MEDIA_ROOT setting to determine the value of the url attribute.