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.
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')],
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)
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'm using Django building a website and I'm trying to let the user upload an image to be used, here is my files :
settings.py
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home2/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
models.py
class test1(models.Model):
dress_name = models.CharField(max_length=250, default='dress')
dress_size = models.CharField(max_length=50, default='5')
docfile = models.FileField(upload_to='documents/%Y/%m/%d',default ='upload')
views.py
def home(request):
all_dress = test1.objects.all()
context = {
'all_dress': all_dress,
}
return render(request, 'fostania/home.html', context)
and here is how I used it in my template
HTML
{% for item in all_dress %}
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="{{ item.docfile.url }}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{ item.dress_name }}</h5>
<p class="card-text">{{ item.dress_size }}</p>
Go somewhere
</div>
</div>
{% endfor %}
URLS.py
from django.contrib import admin
from django.template.context_processors import static
from django.urls import path
from django.contrib.auth import views as auth_views
from dress import settings
from fostania import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', auth_views.login, name='login'),
path('home/',views.home, name='home'),
path('add/',views.add, name="add"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
finally, the image never shows .. it is always an error in the link !!
Please note that image goes there in the static/media file after uploading, So i think it is some kind of URL error!
ERROR
The error is that the image always shows a broken link, and when I open the link (Open images link ) it gives me this error
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/documents/2018/05/18/test_dress3.jpg
You need to add MEDIA_URL to the project's urlpattern list:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Check related part of the doc.
SOLVED
it was a wrong import reference, I used from django.conf.urls.static import static instead of from django.template.context_processors import static and it worked.
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.