Images not loading Django website - django

Images on my django website are not loading for some reason
This is my models.py
thumbnail = models.ImageField(upload_to='images/',blank=True)
This is my settings.py lines
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
if DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, 'static/static-only')
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/static'),
)
This is my views.py
class BlogIndex(generic.ListView):
queryset = models.Entry.objects.published()
template_name = "index.html"
paginate_by = 5
In url.py
if settings.DEBUG:
urlpatterns +=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
In index.html i did this
<img class="img-rounded" src = "{{object.thumbnail.url}}"/>
pip freeze
Django==1.11.2
django-ckeditor==5.2.2
django-crispy-forms==1.6.1
django-markdown==0.8.4
django-pagedown==0.1.3
Markdown==2.6.8
olefile==0.44
Pillow==4.1.1
The Images are getting saved in the static/media/images directory
But the images are not loading in the web page...
When i try to right-click and view the image It shows this error SCREEN SHOT
Other objects are working perfectly.. Only the images aren't loading

You need the media url in the src:
<img class="img-rounded" src = "{{object.thumbnail.url}}"/>
should be:
<img class="img-rounded" src = "{{MEDIA_URL}}{{object.thumbnail.url}}"/>
or something similar
<img class="img-rounded" src = "/static/media/uploads/{{object.thumbnail.url}}"/>

The Issue is fixed, (Got assistance from a facebook group)
The issue was a url pattern in the views.py
The screen shot that I put had a line
Raised by : blog.views.Blogdetail
Apparently i had a urlpattern
url(r'^(?P<slug>\S+)/$', views.BlogDetail.as_view(), name='entry_detail'),
My pattern for blog detail view has match \S+ - so any string of characters that has no spaces in
Which will match pretty much any pattern that hasn't matched previously and any other url pattern which are below this particular url will not be accessed
Changed the url pattern to the following and I was good to go
url(r'^(?P<slug>[-\w]+)/$', views.BlogDetail.as_view(),name='entry_detail'),

settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
in this model you can see Overwrite of exist IMG, return img as base string:
models.py
from django.db import models
from django.core.files.storage import FileSystemStorage
from base64 import b64encode, b64decode
class OverwriteStorage(FileSystemStorage):
def get_available_name(self, name, max_length=700):
if self.exists(name):
os.remove(os.path.join(settings.MEDIA_ROOT, name))
return name
def upload_location(instance, filename):
return os.path.join('defaultfolder', instance.phone, filename)
class ImgModel(models.Model):
name= models.CharField(max_length=100)
img = models.FileField(storage=OverwriteStorage(),
upload_to=phone_upload_location,
null=True,
blank=True,
max_length=700)
def image_to_base64(self, model_picture_path):
if model_picture_path:
try:
with open(model_picture_path.path, "rb") as imageFile:
str = b64encode(imageFile.read())
return "data:image/jpg;base64,%s" % str.decode()
except IOError:
return model_picture_path.url
else:
return None
.html
<img src="{{ MEDIA_URL }}foo.jpg">

I faced this issue and I tried lot of things but imges wont load then I tried out a simple trick but this did the job. What I did was, in my settings.py file, I included the STATIC_DIR varaible just after BASE_DIR. Below is my settings.py file
Settings.py
#Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,"static")
#Other content
STATIC_URL = '/static/'
STATICFILES_DIRS=(
STATIC_DIR,
)
Check this out maybe this will help!

How to fix images answer is
mention above index.html
{% static 'travello/images/' as baseUrl %}
path
then

Related

Django PDF media files are not displayed on my web page

I have been looking on the internet all over the place for this
and it seems that everything is in check, also media images are very well displayed
so I have a django web app that has a FileField where you can upload pdfs and now I am trying to display thouse pdfs but they get displayed with the error as the image below shows.
settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
X_FRAME_OPTIONS = 'SAMEORIGIN'
show_pdf.html
<iframe
src="{{pdf.url}}"
frameBorder="0"
scrolling="auto"
height="1200px"
width="1200px"
></iframe>
models.py
class File_pdf(models.Model):
title = models.CharField(max_length=50)
pdf = models.FileField(upload_to='portfolio/pdfs')
main_resume = models.BooleanField(default=False,help_text="set only one pdf as the main pdf for the main page")
def __str__(self):
return self.title
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('portfolio.urls')),
path('blog/',include('blog.urls'))
]
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
views.py
def pdf_view(request,pdf_id,resume):
dic = {}
if resume == "yes":
pdf_files = File_pdf.objects.filter(main_resume=True)
pdf_file = pdf_files[0]
dic['pdf'] = pdf_file.pdf
dic['title'] = pdf_file.title
else:
pdf_files = get_object_or_404(File_pdf,pk=pdf_id)
pdf_file = pdf_files[0]
dic['pdf'] = pdf_file.pdf
dic['title'] = pdf_file.title
The error looks like this:
this is actually the correct link
In your settings.py add the following code:
X_FRAME_OPTIONS = 'ALLOW-FROM <your localhost URL>'
for example
X_FRAME_OPTIONS = 'ALLOW-FROM http://127.0.0.1:8000/'
it turns out that everything was correct but the brave cache somehow was in conflict with the X_FRAME_OPTIONS updating itself. so after deleting brave's cache it was enough :)

How to generate link for file download?

I created a model without using FileField() and saved the url into path field. Now while displaying I can see the attributes but I cannot download the file. href treats it as a page and i get an error saying GET request failed.
I need to do the same for static files also.
models.py looks like this:
import os
from django.conf import settings
from django.db import models
# Create your models here.
class Document(models.Model):
code = models.CharField(max_length = 50)
path = models.CharField(max_length = 500)
date_of_submission = models.CharField(max_length = 50)
type = models.CharField(max_length = 50)
title = models.CharField(max_length = 200)
department = models.CharField(max_length = 50)
subject = models.CharField(max_length = 100)
updation_allowed = models.CharField(max_length = 1, default = '0')
#property
def relative_path(self):
return os.path.relpath(self.path, settings.MEDIA_ROOT)
template has some code like this:
<a href = '{{ MEDIA_URL }}{{ value.thesis.relative_path }}'> Thesis </a>
*static files*
<a href='/uploads/report.pdf'> Front Page</a>
I tried using the property and provinding the path myself.
urls.py (project/urls.py)
from django.conf.urls.static import static
urlpatterns = [
...
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
...
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
To allow file downloading you need to create a separate view with FileResponse as a response. This view will take some unique argument (I suppose it will be relative path to the file) with url provided in html template. Inside this view, FileResponse will open your file by provided path and then will return response with your file. I think you should do it like this:
Views.py:
def download_file(request, relative_path): # this is a view with file response
media_root = settings.MEDIA_ROOT
return FileResponse(open(f"{media_root}\{relative_path}", "rb"), as_attachment=True, filename="some_name.smth")
template:
<a href = '{% url "download" relative_path=value.thesis.relative_path %}'> Thesis </a>
*static files*
<a href='/uploads/report.pdf'> Front Page</a>
urls.py:
urlpatterns = [
path("download-file/<slug:relative_path>/", views.download_file, name="download")]
You will need to combine with PATHes to get it to work.

Django ImageField Image Not Displaying

I'm trying to use Django 2.0. I'm using the development 'runserver' right now, so please keep in mind that I'm not in production yet. I am familiar with the differences between the two with regard to static files.
I have a Blog Post model. In the admin, I want to be able to add an image to my model using ImageField. I'd like it to be optional, and provide a default image if none is added.
I am able to load images in admin. I am unable to render my image in my template. The console shows that Django is trying to GET my image, but my configurations have not worked so far.
Here's my model and relevant field:
from PIL import Image
class Post(models.Model):
....
thumbnail = models.ImageField(default='/img/default.png', upload_to='img', blank=True, null=True)
....
My model works well aside from the ImageField. My View works well, and I don't think there is any issue there.
Here is my urls.py
....
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
....
path('posts/', views.PostListView.as_view(), name='post_list'),
path('post/<int:pk>/', views.PostDetailView.as_view(), name='post_detail'),
path('post/random/', views.random_post, name='random_post'),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I'm not at all sure about how to handle static files vs. media files in my urls.py, especially with changes to Django in version 2.0.
Here's my relevant settings.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
....
'django.contrib.messages.context_processors.media',
....
]
},
},
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
MEDIA_URL = '/media/'
I am equally unsure of what to put in my settings.py concerning media. My static CSS files are working just fine. I have a logo image in my static files that is rendering in my base template.
Here is my template tag for the ImageField:
<img class="card-image mr-3" src="{{ post.thumbnail.url }}" alt="Generic placeholder image">
Lastly, my /static folder and my /media folder are in the same directory. These are both in my app directory, /blog.
Can anyone see any blaring errors here, or can they make suggestions? My issue is the default image is not loading. The default image IS in the correct directory /media/img/. The console warning says "Not Found: /media/img/default.png".
Thanks in advance. Any suggestions will be helpful.
Django ImageField for Admin Panel
There is important thing you have to define your MEDIA_URL in urls.py.
Without this definition framework doesn't gives to you permission to access image
Setting.py
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
urls.py
if settings.DEBUG: # new
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Models.py
class Product(models.Model):
title = models.CharField(max_length=150)
image=models.ImageField(blank=True,upload_to='images/')
def __str__(self):
return self.title
def image_tag(self):
return mark_safe('<img src="{}" height="50"/>'.format(self.image.url))
image_tag.short_description = 'Image'
Admin.py
class ProductAdmin(admin.ModelAdmin):
list_display = ['title','image_tag']
readonly_fields = ('image_tag',)
Printing the media root helped me solve this issue. Thanks Alasdair.
I don't think there was any issue with my model field above.
The urls.py code that I ended up using is directly from Django docs for Django 2.0 in handling static files https://docs.djangoproject.com/en/2.0/howto/static-files/.
The changes I made to Settings were done thanks to printing my MEDIA_ROOT in the console. I changed the syntax and the direction of a slash (blog\media). I also deleted the context processor shown above in my TEMPLATES options.
Here's what works for me:
models.py
thumbnail = models.ImageField(default='img/default.png', upload_to='img', blank=True, null=True)
urls.py
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'blog\media')
MEDIA_URL = '/media/'
print(MEDIA_ROOT)
Template tag
<img class="card-image mr-3" src="{{ post.thumbnail.url }}" alt="Generic placeholder image">

Django - uploading static image as default ImageField file

This is my models.py:
def get_profileImage_file_path(instance, filename):
return os.path.join('%s/uploadedPhotos/profileImages' % instance.user_id, filename)
class UserExtended(models.Model):
user = models.OneToOneField(User)
profileImage = models.ImageField(upload_to=get_profileImage_file_path, default='/static/images/myProfileIcon.png')
Now, I want the default image (which is in my static folder) to save to the path given in the
get_profileImage_file_path
function. In my settings.py, I have defined media_root and media_URL as:
MEDIA_ROOT = '/home/username/Documents/aSa/userPhotos'
MEDIA_URL = '/media/'
For some reason, when I pass the user object in the template and in the template, if I do:
<img class='profilePic' src="{{ user.userextended.profileImage.url }}" height='120px' alt="" />
No image shows up and when I open up the 'inspect element' section in chrome, it gives a 404 error saying:
GET http://127.0.0.1:8000/home/username/Documents/djcode/aS/aSa/static/images/myProfileIcon.png 404 (NOT FOUND)
even though that is the correct file path to the image. (I'm also not sure why it's giving the entire file path, isn't it just supposed to start from /static/? Even when I 'view source', the entire url is there.) How do I make it so that the default image which is located in the static folder uploads to the path provided in the
get_profileImage_file_path
function?
In general we use the config as follows for media :
BASE_DIR = dirname(dirname(abspath(__file__)))
MEDIA_ROOT_DIR = 'media'
MEDIA_ROOT = normpath(join(BASE_DIR, MEDIA_ROOT_DIR))
MEDIA_URL = '/media/'
For, development purposes set :
DEBUG = True
And in urls.py add the following :
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)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Upload the image again and validate the Image, it should work now.

Failing to show images in templates Django

I have problems showing images in my Django templates (I'm uploading the images from the admin application). I read the documentation and other posts about the upload_to and still couldn't figure it out. I tried this <img src="{{ a.image}}"/> in my template and then this <img src="{{MEDIA_URL}}{{ a.image}}"/> and same results. Here is my settings.py code :
MEDIA_ROOT = '/home/mohamed/code/eclipse workspace/skempi0/media'
MEDIA_URL = '/media/'
and finally, I tried the following in my models.py and I failed miserably:
image = models.ImageField(upload_to = "ads/")
image = models.ImageField(upload_to = ".")
and when I used image = models.ImageField(upload_to = MEDIA_URL) I got the following error
SuspiciousOperation at /admin/advertisments/banner/add/
Attempted access to '/media/cut.jpg' denied.
EDIT
Generated links are as follows :
<img src="./DSCN6671.JPG">
RE-EDIT
Here is my view:
def index(request):
spotlightAlbum = Album.objects.filter(spotlight = True)
spotlightSong = Song.objects.filter(spotlight = True).order_by('numberOfPlays')
homepage = Song.objects.filter(homepage = True).order_by('numberOfPlays')
ads = Banner.objects.all()
copyright = CopyrightPage.objects.get()
try:
user = User.objects.get(userSlug = "mohamed-turki")
playlists = UserPlaylist.objects.filter(owner = user.userFacebookId)
purchase = Purchase.objects.filter(userName = user.userFacebookId)
user.loginState = 1
user.save()
except:
user = None
playlists = None
context = {'copyright':copyright, 'ads':ads, 'spotlightSong':spotlightSong,'spotlightAlbum': spotlightAlbum, 'homepage':homepage, 'user':user, 'playlists':playlists, 'purchase':purchase }
return render_to_response('index.html',context,context_instance = RequestContext(request))
Could anybody tell me what am I doing wrong??
P.S I'm using Django 1.4
The path you provide in upload_to will be a relative path from the MEDIA_ROOT you set in your project's settings file (typically settings.py).
Your MEDIA_ROOT is where your uploaded media will be stored on disk while the MEDIA_URL is the URL from which Django will serve them.
So if your MEDIA_ROOT is /home/mohamed/code/eclipse workspace/skempi0/media and your model's image attribute is:
image = models.ImageField(upload_to = "ads/")
Then the final home on disk of your uploaded image will be /home/mohamed/code/eclipse workspace/skempi0/media/ads/whatever-you-named-your-file.ext and the URL it will be served from is /media/ads/whatever-you-named-your-file.ext
Setting your upload path to be settings.MEDIA_URL won't work because that's where the media is served FROM not where it is allowed to be stored on disk.
If you want to load your uploaded image in your templates just do this (replace whatever with the name of the variable sent from the view to the template that represents this object):
<img src="{{ whatever.image.url }}"/>
The image attribute on your model isn't actually an image, it's a Python class that represents an image. One of the methods on that ImageField class is .url() which constructs the path to the URL of the image taking into account how you set your MEDIA_URL in your project's settings. So the snippet above will generate HTML like this:
<img src="/media/ads/whatever-you-named-your-file.ext"/>
RequestContext() and settings.TEMPLATE_CONTEXT_PROCESSORS
Since the render_to_response() you are returning from your view is utilizing RequestContext() you need to make sure you have settings.TEMPLATE_CONTEXT_PROCESSORS set correctly. Check out the 1.4 docs for further clarification.
upload_to needs to be an absolute path to the directory, not the web url. So try this:
image = models.ImageField(upload_to = settings.MEDIA_ROOT)
in your templates, just use
<img src="{{ a.image.url }}">
First, I suggest to change the MEDIA_ROOT to be
MEDIA_ROOT = os.path.join(PROJECT_ROOT,'media')
this way you ensure the media directory path is right under your project root. Your MEDIA_URL is set up correctly, but it is not used when uploading a file. MEDIA_ROOT is.
Regarding the file upload, in your model set the field to be
image_field = models.ImageField('Image', upload_to='images/some_sub_folder')
Note that I didn't use neither a leading nor trailing forward slashes. The above will upload the image to PROJECT_ROOT/media/images/some_sub_folder/ with the filename and extension of the original file. Alternatively, you can alter the filename by using a callable - upload_to=filename_convetion - more info here.
In your template, you can access the image using
<img src="/media/{{ your_model.image_field }}" />
Hope this helps, cheers.
I know this question is old but I had the same problem and this solved in my case:
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_DIR = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(PROJECT_DIR, "media")
MEDIA_URL = '/media/'
urls.py
Then, my urls.py was missing this line of code to discover the /media/ folder and show the content:
urlpatterns += staticfiles_urlpatterns()
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}, name="media_url"),
) + urlpatterns
Hope it can help someone.