My problem is I am unable to use images in templates that are uploaded by an admin with admin interface. I have configured my settings and URLs according to documentation.
In browser inspect element it is showing
<img src(unknown)>
Uploaded image by an admin using admin interface is stored in the /media/ which is media root.
Location of the image is
/media/img/imagename.jpg
settings.py
# media
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py (my project url file)
from django.conf import settings
from django.conf.urls.static import static
## urlpatterns here
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_URL)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_URL)
models.py
class AboutMe(models.Model):
image = models.ImageField(upload_to='img')
## other fields
views.py
def index(request):
aboutme = models.AboutMe.objects.all()
context = {'information': aboutme,}
return render(request, 'portfolio/index.html', context)
template/index.html
{% for info in information %}
<img src="{{ info.inage.url }}"/>
<div class="name-profile t-center">
<h5 class="uppercase">{{info.name}}</h5>
</div>
{% endfor %}
Related
website: https://willpeoples1.pythonanywhere.com/
I deployed a personal portfolio project using pythonanywhere.com's server and my instructor sent me a video explaining why my media files weren't loading properly (https://d.pr/v/RARFcF). However, I couldn't understand why he was telling me to change the pathname of the image in my HTML b/c I am using a template in the img-tag. Any clue where I should go from here? Thanks
settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URLS = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
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
from portfolio import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('blog/', include('blog.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
home page HTML file:
<div class="conatainer text-center">
{% for proj in Projects %}
<hr>
<h2>{{ proj.title }}</h2>
<p>{{ proj.description }}</p>
<img src= "{{ proj.image.url }}" target="_blank" height="300" width="300">
<br>
<br>
{% endfor %}
</div>
This is all set. There was a spelling mistake in my settings.py file. I wrote "MEDIA_URLS" instead of "MEDIA_URL".
I've deployed a project on a web server. In my project everything is working fine but I'm unable to print an image on the profile page. On my local environment everything is working fine but on the deployed version I'm getting the following error: Not Found: /media/media/photos/e.jpg in django.
models.py
class Matr(models.Model):
photo = models.ImageField(upload_to='media/photos/', null=True,
blank=True)
settings.py
MIDIA_ROOT=os.path.join(BASE_DIR,'media')
MEDIA_URL='/media/'
urls.py
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
profile.html
{% if user.matr.photo %}
<img src="{{ user.matr.photo.url }}" width="330">
{% endif %}
Try this
models.py
class Matr(models.Model):
photo = models.ImageField()
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root')
urls.py
if settings.DEBUG:
import debug_toolbar
urlpatterns += [path('__debug__/', include(debug_toolbar.urls))]
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
profile.html
<img src="{{ user.matr.photo.url }}">
And make sure that after uploading photo, you have that photo in 'media_root' library.
I have two apps accounts and home in tutorial project.
A user can create a post in home app and I'm able to render post(i.e images and post data) in home app. In accounts app I want to create a search page where not logged in user can search and view the posts.
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'tutorial/media/')
search.html
{% load static %}
{% if re %}
{% for q in re %}
<a href="{% url 'home:Post_detail' pk=q.id %}">{{q.id}}.{{ q.post }}
<br>
<img src="{{ q.image.url}}" width="240" height="auto">
<p>Posted by {{ q.user.get_full_name }} on {{ q.created }}</p>
{%endfor%}
{% endif %}
I use the above code in both home app and accounts app. It works fine for home app but not for accounts app
when I see view source page I get perfect url in accounts app (search.html) but, the images are not loading properly screenshot
project urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('accounts/', include('accounts.urls' , namespace='accounts') ),
path('home/', include('home.urls' , namespace='home') ),
path('admin/', admin.site.urls),
path('',login_redirect , name = 'login_redirect'),
]
if settings.DEBUG is True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
tutorial project structure
tutorial
|_accounts
|_home
|_tutorial
|_media
|_profile_images
|_all image files
Created new item with name, description and an image with django admin and attached image and I saw the image pop into the media folder on the server as it was uploaded. I passed the item from view to template. The item name, description showed up in the website but the image ('image.jpg') did not. Any ideas? Maybe nginx is causing the image to stay concealed? I'm using nginx, gunicorn, django.
note: on Chrome, it shows a torn image icon. The source code on the browser shows <img src="image.jpg/">. I noticed that the static files are in the format : <img src="static/app1/image123.jpg and display fine. Perhaps my problem image should have media/app1/...?
My ultimate goal is to disaply a graph/image BUT this image is frequently overwritten, with changes, in the media folder from a separate app on the server. This way the viewer can get the latest image.
abridged file structure, for easy viewing:
-website1
-media
image.jpeg
+static
-app1
-templates
-app1
index.html
layout.html
-website1
settings.py
..
website1 urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import include, url
from django.conf.urls.static import static
from website1 import settings
urlpatterns = [
path('admin/',admin.site.urls),
path('app1/',include('app1.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
app1's urls.py:
from django.conf.urls import url
from . import views
from django.urls import path, include
urlpatterns = [
path('', views.index,name='index'),
]
settings.py:
...
...
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = '/media/'
MEDIA_ROOT= 'media/'
views.py:
from django.shortcuts import render
from django.http import HttpResponse
import datetime
from PIL import Image
from django.core.files import File
from django.conf import settings
from io import BytesIO
import os
from app1.models import Item
def index(request):
now = datetime.datetime.now()
return render(request,'app1/index.html', {
'Data':now,
'itemContext':Item.objects.get(id=1)
})
index.html:
{% extends 'app1/layout.html' %}
{% block content %}
<h1 align="center">{{Data}}</h1>
<h2 align="center">
{% load static %}
<img src="{% static "sentiment_analysis/image.jpeg" %}" alt="No immage"/>
</h2>
<h4>
{{itemContext.name}}
{{itemContext.description}}
<img src="{{ itemContext.image }}"/>
</h4>
{% endblock %}
app1's models.py:
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=32)
description = models.TextField()
image = models.ImageField(blank=True, null=True)
def __str__(self):
return self.name
nginx/sites-avilable.conf:
...
...
root /usr/share/nginx/html;
index index.html index.htm;
location /static/ {
alias /home/jeff/website1/static/;
}
location /media/ {
alias /home/jeff/website1/media/;
}
...
...
[SOLUTION WAS A FILE PERMISSIONS ISSUE... SEE COMMENTS]
in the image src you have double double quotes so the src isnt working replace it with that and you should be good
<img src="{% static 'sentiment_analysis/image.jpeg' %}" alt="No immage"/>
eidt your code is like that
<img src="{% static " #this quotes ends here
sentiment_analysis/image.jpeg # this isnt inside any quotation
" %}" # second quotation start and end here
in here you should relace :
<img src="{{ itemContext.image }}"/>
with this
<img src="{{ itemContext.image.url }}"/>
I'm new to django and I've been playing around with uploading pictures then displaying them. ... well trying to display them.
Whenever I try to display the image from a template, I just get the broken image link icon.
I'm using the sqlite3 server
settings.py
ROOT_DIR = os.path.dirname(os.path.dirname(__file__))
def location(f):
return os.path.join(ROOT_DIR, f)
MEDIA_URL = 'http://127.0.0.1:8000/media/'
MEDIA_ROOT = location('media/')
models.py
class Image(models.Model):
image = models.ImageField(upload_to = 'images/')
views.py
from imageupload.settings import MEDIA_ROOT, MEDIA_URL
def main(request):
imgs = Image.objects.all()
return render_to_response('index.html', {'images': imgs, 'media_root': MEDIA_ROOT, 'media_url': MEDIA_URL})
url.py
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Right now I've just used the admin to upload images. And that seems to work fine, they go to where I expect
But when I try to display them:
template
<!DOCTYPE html>
<html>
<img src="<correct path to project>/media/images/photo_1.JPG" />
{% for img in images %}
<img src="{{ media_root }}{{ img.image.name }}" />
<img src="{{ media_url }}{{ img.image.name }}" />
<img src="{{ img.image.url }}" />
{% endfor %}
</html>
I get the broken icon for each one.
The browser source code shows me:
<!DOCTYPE html>
<html>
<img src="<correct path to project>/media/images/photo_1.JPG" />
<img src="<correct path to project>/media/images/photo_1.JPG" />
<img src="http://127.0.0.1:8000/media/images/photo_1.JPG" />
<img src="http://127.0.0.1:8000/media/images/photo_1.JPG" />
</html>
that makes sense, I only have one photo uploaded.
and if I copy one of the hard links and put it into some other html file ...it works
Oh FFS....
aperently it's
MEDIA_URL = '/media/'
NOT
MEDIA_URL = 'http://127.0.0.1:8000/media/'
...despite #'http://127.0.0.1:8000/media/' being written right next to it
working img link looks like so:
<img src="/media/images/photo_1.JPG" />
you definitely need the:
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in the url file also
For me, I did the following two things:
Define media url in the settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
and then in the project's urls.py, defined serving url for development and production purpose:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('django_app.urls')),
]
# Serving the media files in development mode
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
else:
urlpatterns += staticfiles_urlpatterns()
then you can reference the image in the media folder in the template like this:
<img src="media/path_to_image" />
Note: Don't forget to set the DEBUG flag to False in the settings.py for production.
if you are looking for display images in development environment try this:
settings.py
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(SITE_ROOT, 'static')
MEDIA_URL = '/static/'
STATIC_ROOT = os.path.join(SITE_ROOT, 'statics')
STATIC_URL = '/statics/'
urls.py
# somebody import this from settings
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$','django.views.static.serve',
{'document_root': os.path.join(SITE_ROOT, 'static')})
)
html view file *.html:
<img src="{{ MEDIA_URL }}img/content_top_edit_form.png">
this means we have a img folder in static folder. in your case you can change this by
if you see your browser html must be seen like this:
<img src="/static/img/content_top_edit_form.png">
in the template use {{img.image.name.url}}