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.
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 building a project in Django 3, but the images aren't linking in the files.
All images are store in a folder called media & here's the HTML for my logo for example -
<a class="navbar-brand" href="{% url 'index' %}">
<img src="{{ MEDIA_URL}}logo.png" height="70" class="pr-4" alt="Site logo">
Then I've this in my settings -
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
and in my project level URLS I've got -
from django.conf import settings
from django.conf.urls.static import static
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You should use static folder for the static content like images, css, js etc... and media for the dynamic content like uploads from users, avatar pictures... then you should use this template tag:
{% load static %}
<a class="navbar-brand" href="{% url 'index' %}">
<img src="{% static 'logo.png' %}" height="70" class="pr-4" alt="Site logo">
If you want to use media folder anyways, you need to add this in your urls.py (extracted from here) in order to make it work fine in local:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
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.
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.
I'm desperatly trying to load some images to and from my database with the help of Django.
Loading seems to work, but getting them back from the database and showing them on a webpage doesn't seem to work.
Here some info:
Environment:
myproject
|_forpix(my app)
|_myproject
|_media
|_images
|_mimicry3.png
I have a base.html wich includes a contentblock "allimages.html":
{% extends "base.html" %}
{% block content %}
<div id="imagelist">
{% for image in images %}
<p><img src="{{MEDIA_ROOT}}{{image.picture.url}}" />{{ image }}</p>
{% endfor %}
</div>
{% endblock %}
This gives me the following result:
And if I click on one of the images i get:
In my settings.py I've set the following:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates/'),)
Now i really don't know how to fix this.
Can anybody provide me with some help (not the django tutorial, I've been there, tried that)
Do I have to add something in the urls.py especially for the media file? Or is it something else?
If i need to provide extra info, just ask.
^media/$ is a very wrong regex for media files. You should delete the $ (end-of-the-string) sign from this regex.
Usually for development environments I use this snippet in the urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Also remove the useless {{ MEDIA_ROOT }} part from your template code. It should be:
<img src="{{ image.picture.url }}" />
In adition the line that you have to add is..
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
But it has to be in the urls.py of your project folder. not in the urls.py of your App folder. I knew it by mistake.