Django Application Wont Load User Uploaded Image - python

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')],

Related

Image is not being accessed through port 8000(under development)

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)

Django media files not loading

I have a users app, profile is a model created in its models.py.The image is present in /media/profile_pics/ but even after giving the full path in src it is not loading. I cannot figure out why.Adding the relevant files below.
models.py
from django.contrib.auth.models import User
from django.db import models
from django.contrib.auth.models import AbstractUser
class profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='media/default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
profile.html
<!DOCTYPE html>
{% extends 'base2.html' %}
{% load crispy_forms_tags %}
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>profile</title>
</head>
{% block content %}
<body style="margin-left: 300px">
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<img class="rounded-circle account-img" src="E:\py-projects\hello-world\media\profile_pics\profile1.png">
</div>
</div>
</body>
{% endblock %}
</html>
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
print(MEDIA_ROOT)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
urls.py(the main urls.py, not of app users)
from django.contrib import admin
from django.urls import path, include
from users.views import profile
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('users.urls'), name='index'),
path('profile/', profile, name='profile'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
i feel stupid for not seeing this :| had to add this.
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Use this in your urls.py
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve, {'document_root':
settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve, {'document_root':
settings.STATIC_ROOT}),
]
And in your settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'

Django Display ImageField With Media Dir

I am using Django 1.9.3. I am trying to display media files uploaded by say a user (e.g. imageFields).
HTML Page:
{% for project in projects %}
<img src="{{ project.image.url }}" class="img-responsive" alt="">
{% endfor %}
Views.py:
def home(request):
projects = AvailableProject.objects.all().order_by('-published_date')
return render(request, 'accounts/home.html', {'projects': projects})
urls.py:
urlpatterns = [
...
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
('global', os.path.join(BASE_DIR, 'smilesite', 'project_static')),
('admins', os.path.join(BASE_DIR, 'admins', 'static')),
('accounts', os.path.join(BASE_DIR, 'accounts', 'static')),
('mysite', os.path.join(BASE_DIR, 'mysite', 'static')),
('media', os.path.join(BASE_DIR, 'media')),
)
# print(STATICFILES_DIRS)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
)
# Define place to save media (e.g. pictures for all the projects)
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/'
models.py:
from django.db import models
from django.conf import settings
# Create your models here.
class AvailableProject(models.Model):
image = models.ImageField(upload_to=settings.MEDIA_ROOT)
I have literally went through every single stack over flow page on this and tried the following solutions, but still has not worked...:
<img src="{% static 'media/{{project.image.title}}.jpg' %}" class="img-responsive" alt="">
<img src="{{ project.image.url }}" class="img-responsive" alt="">
I don't know why the project.image.url is not showing the corresponding image correctly.
The reason was exactly what Joni Bekenstein said.
I changed this one line and everything worked:
image = models.ImageField(upload_to='uploads/')
Then {{ project.image.url }}, was the correct url.

Images broken while trying to display it from database in django

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.

How can I use user uploaded files in my templates? (django)

So far I made it to the part where a user uploads an image but how can I use those images which are located in my media folder? Here is what I tried :
my view:
#I even tried to import MEDIA_ROOT to use it in my template...
#from settings import MEDIA_ROOT
def home(request):
latest_images = Image.objects.all().order_by('-pub_date')
return render_to_response('home.html',
#{'latest_images':latest_images, 'media_root':MEDIA_ROOT},
{'latest_images':latest_images,},
context_instance=RequestContext(request)
)
my model:
class Image(models.Model):
image = models.ImageField(upload_to='imgupload')
title = models.CharField(max_length=250)
owner = models.ForeignKey(User)
pub_date = models.DateTimeField(auto_now=True)
my template:
{% for image in latest_images %}
<img src="{{ MEDIA_ROOT }}{{ image.image }}" width="100px" height="100px" />
{% endfor %}
and my settings.py MEDIA_ROOT and URL:
MEDIA_ROOT = '/home/tony/Documents/photocomp/photocomp/apps/uploading/media/'
MEDIA_URL = '/media/'
So again here is what I am trying to do: Use those images in my templates!
If you use the url attribute, MEDIA_URL is automatically appended. Use name if you want the path without MEDIA_URL. So all you need to do is:
<img src="{{ some_object.image_field.url }}">
On development machine, you need to tell the devserver to serve uploaded files
# in urls.py
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
{# in template, use sorl-thumbnail if your want to resize images #}
{% with image.image as img %}
<img src="{{ img.url }}" width="{{ img.width }}" height="{{ img.height }}" />
{% endwith %}
# furthermore, the view code could be simplified as
from django.shortcuts import render
def home(request):
latest_images = Image.objects.order_by('-pub_date')
return render(request, 'home.html', {'latest_images':latest_images})
On production environment using normal filesystem storage, ensure the webserver has permission to write to MEDIA_ROOT. Also configure the webserver to read /media/filename from correct path.
ImageField() has an url attribute so try:
<img src="{{ MEDIA_URL }}{{ image.image.url }}" />
You could also add a method to your model like this to skip the MEDIA_ROOT part:
from django.conf import settings
class Image(...):
...
def get_absolute_url(self):
return settings.MEDIA_URL+"%s" % self.image.url
Also I'd use upload_to like this for sanity:
models.ImageField(upload_to="appname/classname/fieldname")
Try these settings:
import socket
PROJECT_ROOT = path.dirname(path.abspath(__file__))
# Dynamic content is saved to here
MEDIA_ROOT = path.join(PROJECT_ROOT,'media')
if ".example.com" in socket.gethostname():
MEDIA_URL = 'http://www.example.com/media/'
else:
MEDIA_URL = '/media/'
# Static content is saved to here
STATIC_ROOT = path.join(PROJECT_ROOT,'static-root') # this folder is used to collect static files in production. not used in development
STATIC_URL = "/static/"
STATICFILES_DIRS = (
('', path.join(PROJECT_ROOT,'static')), #store site-specific media here.
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
For Django version 2.2., try the following:
#You need to add the following into your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
Your URL mapping
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #add this
# And then use this in your html file to access the uploaded image
<img src="{{ object.image_field.url }}">
You have to make the folder containing the uploaded images "web accessible", i.e. either use Django to serve static files from the folder or use a dedicated web server for that.
Inside your template code, you have to use proper MEDIA_URL values.

Categories