Friends,
I am using Django 1.6 and I have for the last week(!) been trying to display photos on a web page that are uploaded via the Django Admin site.
I know this is a common problem. I have tried reading the documentation, numerous SO questions like this one and this one all without success.
After uploading the image via the Admin site, I can see that the image exists in the following folder:
/home/ian/django/mysite/cars/media/images/1.JPG
However when the page loads (or trying to view the image after uploading them via the Admin Site) I see a 404 error. The source for the image shows the following:
<li><img src="/media/images/1.JPG" height="420"/></li>
The model.py has the following field:
photo = models.ImageField(upload_to='images/')
The urls.py has the following added:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The template is:
{% extends "base.html" %}
<h1>Here</h1>
<p>{{ collectiondetail.title }}</p>
{% for photo in photos %}
<li><img src="{{ photo.photo.url }}" height="420"/></li>
{% endfor %}
{% endblock %}
Finally the settings.py are:
STATIC_ROOT = '/home/ian/django/mysite/cars/static/'
STATIC_URL = '/static/'
MEDIA_ROOT = '/home/ian/django/mysite/cars/media/'
MEDIA_URL = '/media/'
What have I missed?
The urls.py snippet you are using is only for development and will only work in debug mode. Everything you have looks correct so double-check that in settings.py DEBUG = True. From the docs on this feature:
This helper function works only in debug mode and only if the given prefix is local (e.g. /media/) and not a URL
Thanks to everyone for helping out. The default permissions when the files were uploaded were ok.
Finally managed to track down the problem to two settings.
MEDIA_URL was previously set to:
MEDIA_URL = '/media/'
Changed this to:
MEDIA_URL = '/cars/media/'
Changed the following in the urls.py file from
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
to
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
And now the images show as expected.
Related
I probably did something stupid but when i upload a image with /admin I can't get it to load.
I made a for loop to get all post's and everything shows except for the image
model:
`class Post(models.Model):
title = models.CharField(max_length=140)
body = models.TextField()
image = models.ImageField(upload_to='blog/media/photos')
date = models.DateTimeField()`
template page:
` {% for post in object_list %}
<h5>{{post.title}}</h5>
<img src="{{ post.image.url }}">
<h1>{{ post.image.url }}</h1>
{% endfor %}`
I would imagine it is related to your MEDIA_URL settings. Check the terminal output and look for the request to the image, there is a good chance you've not set that, and/or you've not added the media url handler to your urls.
https://docs.djangoproject.com/en/2.0/howto/static-files/#serving-files-uploaded-by-a-user-during-development
You must set the media folder path in the settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
or add media root on url.py
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)
Is there a blog/media/photos folder path and accessable?
i want to store a lot of images in a table(model of django) under an attribute 'imgsrc'. How do i do that? i have seen a lot of online material but i am not getting the complete information anywhere. What changes do i need to do in settings.py and where do i store my image files?...
a part of models.py
class elementdetails(models.Model):
sid=models.IntegerField()
imgsrc=models.ImageField()
soundsrc=models.FileField()
sounddesc=models.CharField(max_length=20)
Setup MEDIA_ROOT and MEDIA_URL in you settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
In your urls.py, add:
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)
Make sure to have media directory in your root directory.
Now, you can also use uploaded_to in your model for storing those images in a directory.
class elementdetails(models.Model):
sid=models.IntegerField()
imgsrc=models.ImageField(upload_to='elements/')
soundsrc=models.FileField()
sounddesc=models.CharField(max_length=20)
In order to get the image in templates, use:
<img src="{{ object.imgsrc.url }}" alt="image">
If you want to upload images in forms, make sure to use enctype="multipart/form-data" in template:
<form action="" method="post" enctype="multipart/form-data">
Also, make sure in views, use:
form = Form(request.POST, request.FILES)
It will work.
I have some problems in django,
I can load images in my index.html, but not in other templates,
why is this happening?
Tried many methods and viewed many other post but non work for me.
This is my urls.py
urlpatterns = patterns('',
# Examples:
url(r'^$', 'userboard.views.home', name='home'),
url(r'^items/(?P<UserBoard_id>\d+)/$','userboard.views.details',name='details'),
url(r'^upload.html$', 'userboard.views.upload', name='upload'),
url(r'^items/(?P<UserBoard_id>\d+)/delete.html$','userboard.views.delete',name='delete'),
url(r'^items/(?P<UserBoard_id>\d+)/edit.html$','userboard.views.edit',name='edit'),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
This is my index.html, it works fine
<h1> Your Items: </h1>
<ul>
{% for items in ItemList %}
<li><a href="/items/{{items.id}}/">
<img src="{{items.itemImage}}"></a>
</li>
<hr />
{% endfor %}
</ul>
Add a new item
but this wont load my pictures
<img src="{{item.itemImage}}">
<h1>{{item.itemName}}<h1>
<h2>{{item.itemDesc}}</h2>
<br /><br/><br/>
Delete this item
<br />
Edit this item
i am not sure if you need my views, here they are
def home ( request) :
ItemList= models.UserBoard.objects.all()
return render_to_response('index.html',{'ItemList':ItemList})
def details(request,UserBoard_id):
try:
item=models.UserBoard.objects.get(pk=UserBoard_id)
except models.UserBoard.DoesNotExist:
raise Http404
return render_to_response('details.html' ,{'item':item})
Please let me know where I went wrong or at least give me a hint where I could start searching on.
EDIT:
here are my models
from django.db import models
class UserBoard(models.Model):
itemName=models.CharField(max_length=100)
itemDesc=models.CharField(max_length=400)
itemImage=models.ImageField(upload_to='../media/pictures')
if i print out the value of items.itemImage, it will show this ../media/pictures/d.jpg
Same value in both pages, but image will only show on 1. Templates for both pages are at the same folder.
And here is my settings.py media root
MEDIA_ROOT = '/home/rox/Documents/IP/userboard/media/'
MEDIA_URL = 'media/'
PROBLEM SOLVED
THANKS A LOT to little_birdie and the others out there who helped.
The problem was this . I didn't put the '/' infront of item.itemImage previously.
However, why is it that without the / it works in the index.html but not the others?
Not quite enough information but I think I know what's going on here.
You are getting a relative path from item.itemImage, that is.. it does not start with a slash, so the browser will load it relative to the url of the page the image is on.
Apparently you stored the full url path to your image in your image field, eg:
media/foo/myphoto.jpg
When loaded from / (home page) becomes '/media/foo/myphoto.jpg'.. which works.
The bottom line is, do this:
<img src="/{{item.itemImage}}">
I have these URLs in my project .urls:
urlpatterns = patterns('',
(r'^categories/', include('category.urls')),
)
In the categroy app, my category.urls:
urlpatterns = patterns('category.views',
(r'^$', 'category_tree'),
(r'^add/?$', 'category_add'),)
I have this in my settings.py:
MEDIA_URL = "http://localhost:80/media/"
ROOT_PATH = os.path.normpath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(ROOT_PATH, 'templates'),
)
In the project templates directory there is a base template "base.html" with this line:
<link href="{{MEDIA_URL}}css/base.css" rel="stylesheet" />
In my "category" app, I also have templates "category_tree.html" and "category_add.html".
These both extend from base.html:
{% extends "base.html" %}
The blocks in base.html are rendered correctly with content from these two child templates/views.
But the css and images of category_add.html aren't found.
There is a link on categroy_tree.html like this:
<div>Add category</div>
This points to the correct view if clicked. But then the css MEDIA_URL request changes from
http://localhost/media/css/base.css
// (Correct)
to
http://localhost:8000/categories/css/base.css
// (Incorrect)
Why is this happening and what do I have to do to fix this?
The add category view isn't using a RequestContext to render the page, so MEDIA_URL is not sent to the template context.
I stumbled on a silly situation with Django's RequestContext thing. Here is my question:
I stored all my images in my media/uploads file. In my template I'm simply using :
{% for photo in photos %}
<img src="{{gallery_root}}/{{photo.get_name}}" />
{% endfor %}
My view is :
def gallery_view(request):
photos = Photo.objects.all()
return render_to_response('gallery/sampleGallery.html',{'photos':photos},context_instance=RequestContext(request))
In my settings file :
GALLERY_ROOT = os.path.join(MEDIA_ROOT, "media/uploads")
And i have a contextprocessor file which contains:
from django.conf import settings
def gallery_root(request):
return {'gallery_root':settings.GALLERY_ROOT}
When I open my template, the image's path appears however the server gives 404, the path seems correct but django can not serves them.. So what's the reason that I can not see images on my template ?
The image source appears like this :
<img src="/Users/imperium/Desktop/sample/media/uploads/popo.jpg" />
Hey there, it's probably that your media isn't being served propery.
Try something like this in your urls.py file.
# if we're in DEBUG mode, allow django to serve media
# This is considered inefficient and isn't secure.
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.GALLERY_ROOT}),
)
MEDIA_ROOT is the filesystem path to your media, not the URL path. Building on the suggestion from mongoose_za, your template should look like:
{% for photo in photos %}
<img src="/media/{{photo.get_name}}" />
{% endfor %}
Of course, you can define a new constant in settings.py which corresponds to the URL root you've chosen, and use this both in urls.py as well as in your templates.