How to reload html src of an image in django - python

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.

Related

Save images from Form to database using ImageField Django

I am trying to save images from my Form to my database in django. All of my other CharFields seem to save from my form but not the images. When I go to admin I can upload and save images to a specified media folder and it works however, the images dont seem to save. Please help very confused, also new to this so my code may be a mess, much help is needed. Thanks. Links to my code below:
[updated models][1]
[updated settings][2]
[updated urls][3]
[updated views.py][1]
links to code:
[1]: https://i.stack.imgur.com/Td7Mv.png
[2]: https://i.stack.imgur.com/31vNB.png
[3]: https://i.stack.imgur.com/BXhg7.png
[4]: https://i.stack.imgur.com/fu5BC.png
In your models.py file you need to change all your ImageField to this
media_gallery = models.ImageField(blank=True, null=True, upload_to='photos/%Y/%m/%d/')
This saves the location of the image in the database
Later you can access the image in templates like this
src = "{{ model_name.media_gallery.url }}"
After everything lastly add this code to your settings.py file
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Please update your main project's urls.py file by adding this code at the end
urlpatterns = [] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

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

Cannot load Images from Django ImageField in Template

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!

include image files in Django templates shows broken link?

All,
I've tried the tips found on the forum. Unfortunately i'm still stuck.
The image doesn't appear in the template.
As far as i've traced the errors now they are twofold:
1) one where the picture should appear there is still a broke link and an error message:
Failed to load resource: the server responded with a status of 404 (NOT FOUND),
**http://127.0.0.1:8000/Point3D/grafiek/laptop.jpg**
So it does go in the right path, but can't find the image.. Which is in my MEDIA_ROOT
or I receive:
Resource interpreted as image but transferred with MIME type text/html with:
**http://127.0.0.1:8000/Point3D/grafiek/**
2) The other error is that if i go to : http://127.0.0.1:8000/media/ i get:
Permission denied: /media/
maybe this has something to do with it.
For the rest i've followed roberts solution for now but without any luck..
Any help would be very much appreciated!
What's your template looking like? It's should be something like:
<img src="{{ MEDIA_URL }}Point3D/grafiek/laptop.jpg" alt="" />
I'm guessing the right path for your image should be http://127.0.0.1:8000/media/Point3D/grafiek/laptop.jpg
Are you including {{ MEDIA_ROOT }} in your tag.
Also, make sure you are calling the template with a RequestContext object, because otherwise {{ MEDIA_ROOT }} will not be set in your template. Try using django.views.generic.simple.direct_to_template rather than django.shortcuts.render_to_response. Note that direct_to_template is called just like render_to_response except it takes request as the first argument.
from django.views.generic.simple import direct_to_template
# your view code here
return direct_to_template(request, 'path/to/template.html', **kwargs)
Assuming media on your file system is at:
/home/username/django-project/media/images/favicon.ico
In your settings.py, you should have:
import os
PROJECT_PATH = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.media',
)
Your project urls.py should also contain the following which should only work in DEBUG mode:
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT.replace('\\','/')}, name='media'),
)
Your template should include media like the following:
<link rel="icon" href="{{ MEDIA_URL }}images/favicon.ico" />
Permission denied on /media/ is exactly what is supposed to happen, as otherwise every user of you page could view all the files in that directory (Would be the same as configuring Apache to allow Indexing of a Directory, which is, in allmost al cases, not what you want. Try accessing the file in your browser by pasting the complete url, (and include the media url in your path!):
http://127.0.0.1:8000/media/Point3D/grafiek/laptop.jpg
If that does not work, make sure you have Django or Apache configured to serve the static files you try to access.
edit:
And one more thing that could cause your trouble: /media/ is the default for the admin media url. If your admin media url and your media url are the same thats no good. Change that so your MEDIA_URL and your ADMIN_MEDIA_PREFIX are not the same.

Categories