Retrieving images uploaded by users in Django Templates - python

I understand there are multiple (if not 100s) of questions pertaining to my issue. After trying all, I am here finally to ask. I am able to upload the image and the image path in the model. Example of an image field from model:
<ImageFieldFile: static/image1_FzGpiKx.jpeg>
My static folder is right where the project and app folders are. In similar hierarchy. I have the following settings in my settings.py file:
MEDIA_ROOT = '/static/'
MEDIA_URL = '/'
In my app level urls.py, here is what I have for rendering these images:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
After all this settings , my template shows the following as img src:
/static/image1_FzGpiKx.jpeg
Here is how I render in template:
<img src={{article.image.url}} />
Yet it just renders the typical broken image icon. Can someone help me here? Thank you!

MEDIA_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/static/'
use this in your settings file, and upload a new image and then check it

Related

AttributeError at /media/.. when requesting file in media folder Django development stage

When I am reqeuesting media files (.png in this case) in the media folder in development I get this error:
AttributeError at /media/test.png
This FileResponse instance has no content attribute. Use streaming_content instead.
Request: http://localhost:8000/media/test.png
I added below to the url patterns:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And below to the settings:
STATIC_ROOT = BASE_DIR / 'static'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
Static files are working just fine.
What do I overlook?
Thanks!
hello if you have debug set to True you have to use this:
first go to you settings and set all you static file directories in
STATICFILES_DIRS = [
list of your static file,.......,]
the second step you should have this in your urls.py
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATICFILES_DIRS[0])
note:there is a difference between static_root and staticfile_dirs
static_root is only used for production
this is my mail for more explanation :nguewofoss#gmail.com
I found the problem.
In the newer django version staticfiles are rendered with a streamingHttpResponse, this doesn't have a content attribute.
I found below code in my code that points to the (non existing) content attribute:
if b'<html' in response.content[:100].lower():
I added this to resolve the problem:
if not hasattr(response, 'content'):
return response
if b'<html' in response.content[:100].lower():
Thanks all!

Images are not showing in Production ( DEBUG =False )

I Build a WebApp and I am stuck on a Problem.
Images are not showing in Production (DEBUG = False)
settings.py
MEDIA_ROOT= '/home/new/gitrepo/main/media'
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATIC_ROOT = '/home/new/gitrepo/static/'
What have i tried
I tried python manage.py collecstatic BUT images are still not showing in the Website.
I found many answers on this Topic like THIS. BUT it didn't worked for me.
I don't know what i am doing wrong.
Any help would be appreciated.
Thank You in Advance.
Was it working in development? I think yes
open Pythonanywhere.com => choose "Web" from navbar => scroll to static files
and here you let pythonanywhere know where are the URLs for showing static data from your server
Add those two
URL Directory Delete
/static/ /home/myWebsite/static
/media/ /home/myWebsite/media
The /home/myWebsite/media is a path to where you store the static files for the given URL
here is a screenshot of my configurations
If it's not showing make sure you have something in your main URLS.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

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)

Django: serving user uploaded files

I'm new to Django and Python.I want to display a link to my files stored in my static folder.Here is the required code from settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_URL = "/media/"
When I access these files through my admin I get the following url displayed in my browser:
http://127.0.0.1:8000/media/filename.pdf
Hence what I tried is to give a link to the file in my HTML code :
File
But instead of displaying http://127.0.0.1:8000/media/filename.pdf it just displays /media/filename.pdf which results in an error.
Adding localhost:8000/ before {{instance.docFile.url}} also didn't work.
Why isn't this working?What is the correct way to display link to my files?
Let me know if anything else is required.Thank you.
in your urls.py
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)
in your settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/uploads/'
Then in your template
File
If you want know refer the docs Manage static files
The error is coming because your file is not stored in media.it is stored in static but your database store media URL. change your MEDIA_ROOT (given below) and try to upload one more time
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Don't put slash
:
File
Please see the Django setting MEDIA_ROOT documentation to better understand what your trying to do.
First MEDIA_ROOT and STATIC_ROOT must have different values.
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/'
See static files documentation for more details.
Second, You need to add these settings to your base urls.py.
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)
If you want to use {{ MEDIA_URL }} in your templates, add 'django.template.context_processors.media' in the 'context_processors' option of TEMPLATES in settings.py.
At the top of your HTML page add {% load static %} then to display your media:
<img src="{{ MEDIA_URL }}{{ docFile }}" alt="test">
Please take your time with the Django Documentation, trust me it will help and also checkout the File upload settings

Django - serving user uploaded images

I am having some problems with serving user uploaded files from my Django application:
from models.py:
class Picture (models.Model):
title = models.CharField(max_length=48)
date_added = models.DateTimeField(auto_now=True)
content = models.ImageField(upload_to='pictures')
From the Django admin the files get uploaded to the user_res/pictures/ folder.
from the project's settings.py:
MEDIA_ROOT = 'user_res'
MEDIA_URL = '/user_res/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
Every time I try to reference a static resource (namely css or js files), everything works fine using URLs such as
http://localhost:8000/static/<subfolder>/main.css.
However, I cannot access user uploaded files (which get created by the admin interface in the user_res/pictures folder with a relative URL such as
user_res/pictures/test.jpg
the URL is dynamically created with this line of code from a Django Picture model callable:
return '<img src="{}"/>'.format(self.content.url)
I have no dedicated url-s for either static or media files in the url.py file.
Does anybody have any idea as to how to make Django serve the media files? I understand that for live environments I will need to configure an http server to serve that particular directory, but for now I want to maintain a lightweight development suite.
Thank you.
Edit your urls.py file as shown below.
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)
edit your projects settings.py to look like:
#Rest of the settings
MEDIA_URL = '/media/'
MEDIA_ROOT = 'media'
STATIC_ROOT = ''
STATIC_URL = '/static/'
Please read the official Django documentation about serving files uploaded by a user carefully. Link to docs: https://docs.djangoproject.com/en/1.5/howto/static-files/#serving-files-uploaded-by-a-user
I think the url attribute returns a relative URL ( Django's FileField documentation ), so you should have:
return '<img src="{}"/>'.format(MEDIA_URL + self.content.url)
Relative URLs won't work, as a user visiting "http://localhost/books/" would be requesting "http://localhost/books/user_res/pictures/test.jpg".

Categories