Cannot load Images from Django ImageField in Template - python

I have a project developed with Django in which users have the ability to upload an image through a form in a view. That part seems to be working correctly in that I can bind the data to a form and save the image in a designated folder within the directory that I'm using for the project's database. However when I go to render a page, I get something similar to the following line (the uploaded image has the filename "2220.jpg"):
GET http://localhost:8000/Users/.../project/database/user_uploads/08-30/2220.jpg 404 (NOT FOUND)
Here's the line in my template that renders the image:
<img class="image" src="{{ entry.image.url }}"/>
The relevant parts of my settings.py:
PROJECT_DIR = os.getcwd()
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'database', 'user_uploads')
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
The model containing the image:
def getImagePath(instance, filename):
"""Generates a path to save the file. These are timestamped by the
current date and stored in the databases directory.
Returns:
Path for the file.
"""
date = datetime.date.today().strftime('%Y-%m-%d')
return os.path.join(
os.getcwd(), 'database', 'user_uploads', date, filename)
class Entry(models.Model):
# Other code omitted
image = models.ImageField(upload_to=getImagePath)
I'm guessing there's some URL configuration I'm missing because it seems like it's asking for the image to be served via localhost (or more generally my host name) rather than just a directory on the filesystem. The file location is correct, it just seems to be executing an HTTP request for it instead of just getting it directly. What am I missing? I'm happy to provide any additional information for clarity.
Thank you in advance!

you have to setup media serving.
https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user

In addition to montiniz's answer, the following thread helped me out:
Django MEDIA_URL and MEDIA_ROOT
Basically what I was missing was the URL configuration for serving files from MEDIA_ROOT. One other thing is that calling the url() parameter on a Django ImageField returns the fully qualified URL name - that is, the file's full location. All you need to serve the image from the template is its location within MEDIA_ROOT. In my case, this setting was 'database/user_uploads' and the image was located at '2013-09-02/images/2220.jpg'.
Therefore the url I needed was:
'localhost:8080/media/database/user_uploads/2013-09-02/images/2220.jpg'.
Hope this helps anyone with the same issue!

Related

How to reload html src of an image in django

My Django app import an image from the media_url and then it goes to the next page and shows the image and goes back to first page then a new image imported and the old image is removed.
The problem is that at the first loop everything is good, in the second loop, it appears that html shows the old image not the new one. how can I apply a reloading in html. here is part of the code:
settings.py:
MEDIA_ROOT = 'media//' # I test the MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = 'media//'
views.py:
def scraping(request):
....
template_name = "scraping.html"
response2 = {'media_root': Config.MEDIA_ROOT, 'media_url': Config.MEDIA_URL}
return render(request, template_name, response2)
scraping.html
<img src='{{media_url}}/pic.jpg//'> # I also tried {{media_url}}pic.jpg
{{media_url}}/pic.jpg/
{{media_url}}//pic.jpg//
You can try the code below :
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media')
Well, I didn't got any answer yet, but I realize something. first I changed the media directory to static.
here it is:
scraping.html
<img src='{{static_url}}/' \>
<img src='{{static_url}}//' \>
<img src='{{static_url}}///' \>
each time I have to add a "/" in src to reload my image as it is right now.
if I delete one "/" after refreshing it goes to previous image.
I played a lot in settings and views and html by replacing "/" and "\" but I don't have any clue why its happening
Well, I didn't find any answer for my question, but I solved my problem bypassing this issue.
In the previous version, I tried to import an image , rename it into pic.jpg and call it on the html file. this caused the web to show me all the pre-removed pic.jpg.
Now, I rename all the imported image to a specific name (by date.now()) and this helped html not to get confused by the similar name of the files.
But still I don't know why the html file wouldn't refresh the image even if the name of the source files are the same.

Correct way to save an image in admin and showing it in a template in Django

I am using MySql and Django. I need to select the image route stored in the database, I can't use the url property of an ImageField, It must be the route stored in the database.
First of all, this is my configuration in settings:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
MEDIA_ROOT = PROJECT_ROOT + '/archivos/'
MEDIA_URL = '/archivos/'
My first try on the model was this:
foto = models.ImageField(upload_to = settings.MEDIA_ROOT)
And the URL saved on the database was this:
/home/developer/project/mysystem/archivos/hombre.png
Later I tried this on the model:
foto = models.ImageField(upload_to = '')
And the new URL is this:
./pantalonazul_pXNLcuF.jpg
In both cases the image is uploaded to the MEDIA_ROOT folder, but when I try to use the URL saved on the database, the image doesn't shows. I am changing the src with jquery, I thougth that was the problem, but no, because I putted by hand both URL's in an image, and none of them worked. Also tried this: ../../archivos/pantalonazul_pXNLcuF.jpg but produced the same bad results.
When I enter to the admin, it shows this:
And if I click on that link I get this URL on Address bar:
http://127.0.0.1:8000/archivos/pantalonazul_pXNLcuF.jpg
I also tried to use that URL in the image, written by hand on the src property, but didn't worked.
As an extra, when I click on the link to get that last URL, I have an error that says that the URL is not registered on the urls.py file, shows me a list of my URL's and at the end says this:
The current URL, archivos/pantalonazul_pXNLcuF.jpg, didn't match any of these.
What I'm doing wrong? Why I cant get the image? Is something in the settings or where?
P.S.: The folder where I save the images is outside my app folder, is on the "general" folder, or I don't know how to call it, is in the same folder where settings.py is located, the folders are something like this:
-MyAppFolder
-MySystem
-archivos
-image1.jpg
-image2.jpg
-settings.py
-urls.py
-wsgi.py
I have found a partial solution, reading this Settings Media URL and after it redirected me to this Servinge files during development.
I'm using the last model, the one with the empty uploaded_to and just added the line that the docs recommend on the second link to the urls.py file, and also call the image on this way: ../../archivos/image.jpg but it says that the urls.py solution only works for development, not for serving it as a web page/application, so, someone knows how to make it work in a real server? without using DEBUG=true on settings?

django get media directories in view or model

I have a model where I I am writing a function to upload files :
def get_upload_file_name(instance, filename):
return "my_files/{}".format(filename)
In my settings I have
MEDIA_ROOT = os.path.join(BASE_DIR, 'static')
My static structure
static
css
img
js
my_files
Here I dont want to return hardcoded my_files I want to return from setting like
{{MEDIA_ROOT}}/{}".format(filename)
or something like that...
How can I do this ?
To answer the question you actually asked, you can access your MEDIA_ROOT setting (and any other Django settings) in your views and models with:
settings.MEDIA_ROOT
As mentioned however, you probably want to read up on how media is handled in Django first.
Read about using settings in python code in the docs.
I figured it out!
You can access like this
modelName.fieldName.field.upload_to

Django serving dynamic Files

I have a problem about serving admin uploaded files in my templates.
I set:
MEDIA_URL='/media/'
MEDIA_ROOT = 'assets/'
and my models are like:
mainPhoto = models.ImageField(upload_to="articles/")
When in my templates, I try:
<img src="{{MEDIA_URL}}{{article.mainPhoto}}" />
The image doesn't show up on the website.
I found one deprecated solution with the django .serve(), but I hope to avoid using it.
I was looking everywhere and didn't find any answer, so I hope someone here will be able to help me.
There are two parts to make this work. First is the Django configuration. There are really two settings for this which you have already mentioned - MEDIA_URL and MEDIA_ROOT. As already noted in the comments the MEDIA_ROOT has to be an absolute path. For example:
MEDIA_ROOT = `/abs/path/to/project/media/`
Second part is actually serving the files. If you are in production, you NEVER want to serve your static or media files through Django so you should configure Apache or nginx or whatever server system you are using to serve the files instead of Django. If you are on the other hand still developing the app, there is a simple way to make Django serve media files. The idea is to modify your urls.py and use the Django's static files server to serve media files as well:
# urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# other patterns
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
More about this approach at Django docs.
Also FYI, you probably should not use {{MEDIA_URL}}{{article.mainPhoto}} to get the url of an image. This approach will break for example if you will no longer use file system storage for static files and will switch to something different like Amazon S3. It is always a good idea for the storage backend to figure out the url:
<img src="{{article.mainPhoto.url}}" />

Django upload file url problem

I've got this media root:MEDIA_ROOT = '/var/www/hosted/myapp/static/' and this media urlMEDIA_URL = '/static/res/' and I am trying to upload a file using a callable: def get_uploadto(instance, filename):
''' Dummy callable to silence the upload_to field of FileFields '''
return os.path.join('uploads', filename), it uploads the picture on the disk in /var/www/hosted/myapp/static/uploads/ just as planned, but in the admin it creates a link poiting to static/res/uploads, which does not exist. Does anyone know why? Of course, I can simply move the uploads dir within static res, but I am looking for a more elegant solution.
This is the expected behaviour. The files are in
MEDIA_ROOT + 'uploads' + filename
or
/var/www/hosted/myapp/static/uploads/filename
the URL's that point to those files are:
MEDIA_URL + 'uploads' + filename
or
/static/res/uploads/filename
You then need to make sure that your application or hosting environment points the URL to the on disk location. In the dev environment you would have something like this in your urlpatterns:
(r'^static/res/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.dirname(settings.MEDIA_ROOT)}),

Categories