Django : Media Files not displayed in templates - django

I am trying to create a blog and to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for Post images with an ImageField), the image is stored in /media/images correctly. But I can't display the image on my webpage. However, when I inspect my template with GoogleChrome, the path of my files are ok but there is a 500 error (Failed to load resource: the server responded with a status of 500 (Internal Server Error).
Media Settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'core/static'),
)
Project urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin' , admin.site.urls),
path("", include("authentication.urls")),
path("", include("app.urls")),
]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
App urls.py:
from django.urls import path, re_path
from django.conf.urls import include, url
from app import views
from . import views
urlpatterns = [
path('', views.index, name='home'),
url(r'^blog$', views.blog_view, name ='blog'),
url(r'^blog/(?P<id>[0-9]+)$', views.post_view, name ='blog_post'),
re_path(r'^.*\.*', views.pages, name='pages'),
]
Views.py
def blog_view(request):
query = Post.objects.all().order_by('-date')
context = {'post_list' : query}
return render(request, 'blog/blog.html', context)
Template : Blog.html
{% for post in post_list %}
<img src="{{ post.image.url }}" class="card-img-top rounded-top">
{% endfor %}
models.py
class Post(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255, blank=True)
image = models.ImageField(blank=True, upload_to="images/")
When I check in the google chrome console, I notice that my development server tries to read my jpg file as a txt file, I think my problem is related to this anomaly. Anyone have an idea how to solve my problem ?

This is because of CORS error error, your browser URL must be the same as that of the image. For example, if your project URL is http://127.0.0.1:8000/, your images should be http://127.0.0.1:8000/media/images/about-us-2.jpg not http://localhost:8000/media/images/about-us-2.jpg
The CORS policy suggests the "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at $somesite"
you can read more about it at https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors

you can to this
STATIC_ROOT = (
os.path.join(BASE_DIR, 'staticfiles'),
)
STATIC_URL = '/static/'
MEDIA_ROOT = (
os.path.join(BASE_DIR, 'media'),
)
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'core/static'),
)

Related

Django deployment Failed to load resource: the server responded with a status of 404 (Not Found)

I have some product pictures uploaded in media folder that displays fine in development server, but after deployment I receive the 404 ressource not found error.
In settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'node_modules')]
STATIC_ROOT = os.path.join(BASE_DIR, 'productionStatic')
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
In urls.py
from django.contrib import admin
from django.urls import path
from index import views
from index.views import indexPage, hdnytorv
from webshopRestaurant.views import hd2900_webshop_Main, AddressCheckForDeliverability, ChangeItemQuantity
from webshopCustomer.views import TakeawayCheckout, totalPriceDeliveryPossible, DeliveryForm, PickUpForm, localDeliveryCheckoutAddressCheck, Payment, PaymentComplete
from django.conf import settings
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = [
path('admin/', admin.site.urls),
path('', indexPage.as_view(), name = 'index'),
path('hdnytorv', hdnytorv.as_view(), name='hdnytorv'),
path('hd2900', views.hd2900.as_view(), name='hd2900'),
path('hd2900_takeaway_webshop', hd2900_webshop_Main.as_view(), name="hd2900_takeaway_webshop"),
path('check-address-for-deliverable', AddressCheckForDeliverability.as_view()),
path('changeItemQuantityInBasket', ChangeItemQuantity.as_view()),
path('isPriceAboveDeliveryLimit', totalPriceDeliveryPossible.as_view()),
path('hdbynight', views.hdbynight.as_view(), name='hdbynight'),
path('takeawayCheckout', TakeawayCheckout.as_view()),
path('deliveryFormCheckout', DeliveryForm.as_view()),
path('pickupFormCheckout', PickUpForm.as_view()),
path('local_delivery_checkout_is_address_deliverable', localDeliveryCheckoutAddressCheck.as_view()),
path('localDeliveryPayment', Payment.as_view()),
path('paymentComplete', PaymentComplete.as_view()),
]
#When in production medida url must always be added to urlpatterns
#if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
To display the product in view I have in my html template
<img class="card-img embed-responsive-item" src="{% get_media_prefix %}{{ item.product.image_path }}" alt="{{item.meta_description}}">
The pictures are uploaded to this location django_project_folder/media/productImages. I have assured that it is owned by www-data group and also media and all subfolders have 775 access rights. In development server the images shows up all right but in production I got 404 not found error.
This issue is a duplicate. See the answer here I fixed it by adding in urls.py
from django.urls.conf import re_path
from django.views.static import serve
re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),

Django : Media Images not displayed in templates

I am trying to create a blog and to display image for each post. i am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for Post images with an ImageField), the image is stored in /media/images correctly. But I can't display the image on my webpage. However, when I inspect my template with GoogleChrome, the path of my files are ok but there is a 500 error (about-us-2.jpg:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error).
Media Settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'core/static'),
)
Project urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin' , admin.site.urls),
path("", include("authentication.urls")),
path("", include("app.urls")),
]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
App urls.py:
rom django.urls import path, re_path
from django.conf.urls import include, url
from app import views
from . import views
urlpatterns = [
path('', views.index, name='home'),
url(r'^blog$', views.blog_view, name ='blog'),
url(r'^blog/(?P<id>[0-9]+)$', views.post_view, name ='blog_post'),
re_path(r'^.*\.*', views.pages, name='pages'),
]
Views.py
def blog_view(request):
query = Post.objects.all().order_by('-date')
context = {'post_list' : query}
return render(request, 'blog/blog.html', context)
template : Blog.html
{% for post in post_list %}
<img src="{{ post.image.url }}" class="card-img-top rounded-top">
{% endfor %}
models.py
class Post(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255, blank=True)
image = models.ImageField(blank=True, upload_to="images/")
Try this approach:
MEDIA_ROOT = os.path.join(BASE_DIR, "APPName", "media")
MEDIA_URL = "/media/"
You can then find images under:
<img src="media/test.png">
The folder "media" is in the main dir of the Project (not the app!):
Project
media
static
APP
templates
views.py

Django 3.1 media prefix not showing on urls

I am using Django 3.1.
settings.py looks like
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
urls.py looks like
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
my model image field looks like
dev_image_one = models.ImageField(upload_to='dev/', blank=True, null=True, verbose_name = 'image 1')
When files are uploaded, they end up in the /media/dev directory.
When they are to be displayed, the url looks like:
<img src="dev/1.png">
If I manually append /media/ on to the front of the url, the image displays. I never had this problem before so I'm at a loss as to what is going wrong. I never used 3.1 before, so I'm wondering if that doesn't have something to do with it. No problem with the static files. Thanks.
Make sure settings.py be like
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
load {% load static %} in any page that you want to access image
use {% static 'images/india.jpg' %} to acess image

Django is not serving media files uploaded by user on heroku

I have tried everything but somehow i cannot see images uploaded by user.I have deployed code on heroku and every static file is getting loaded properly. User is even going to correct path of image but somehow server is showing errors of not finding image.
Settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
#STATICFILES_DIRS = (
# os.path.join(PROJECT_ROOT, 'static'),
#)
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Models.py
#this is for photos upload by user
class You(models.Model):
user = models.ForeignKey(User,null=True)
name=models.CharField(max_length=30,blank=True,default='pictures/videos')
docfile = models.FileField(upload_to='documents/%Y/%m/%d', null=True,blank=True)
def __unicode__(self):
return self.user.username
#Views.py(To upload files)
#login_required
def upload(request):
if request.method == 'POST':
newdoc = You(docfile = request.FILES['file'],user=request.user)
newdoc.save()
msg='dee'
# Redirect to the document list after POST
return HttpResponse(json.dumps({'message': msg}))
else:
form = DocumentForm()
# Render list page with the documents and the form
return render(request,'mat_upload.html',{'form':form})
Template(gallery.html)
{% for document in documents %}
<img class="img-responsive" src="{{MEDIA_URL}}/media/{{ document.docfile }}" alt="hiiii" style="max-width: 100%;
height: 250px;" />
{% endfor %}
#login_required
def gallery(request):
documents = You.objects.filter(user=request.user)
return render(request,'gallery.html',{'documents': documents,})
Urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import RedirectView
admin.autodiscover()
import harpoons.views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('harp.urls')),
url(r'^password_reset_recover/', include('password_reset.urls')),
url(r'^accounts/', include('allauth.urls')),
]
You cannot save user-uploaded files locally on Heroku. The filesystem is ephemeral, and does not persist across dyno restarts or between concurrent dynos. You need to upload them somewhere more permanent; a popular choice is Amazon S3, and there are plenty of libraries that will do that for you.

MEDIA_URL path doesn't show up

I have a problem with my static and media settings, so my uploaded images doesn't show up on my site page.
In my "settings.py" I have:
MEDIA_ROOT = (
os.path.join(BASE_DIR, '..', 'static', 'media')
)
MEDIA_URL = '/media/'
STATIC_ROOT = (
os.path.join(BASE_DIR, '..', 'static'),
)
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, '..', 'static'),
)
In my "models.py" I have:
expert_photo = models.ImageField(upload_to='profiles')
Some "urls.py":
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
(r'^tinymce/', include('tinymce.urls')),
url(r'^experts/all/$', 'expert.views.experts', name='experts'),
url(r'^experts/get/(?P<expert_id>\d+)/$', 'expert.views.expert', name='expert'),
)
And after all of that, when I go to my page, I see, that the picture have link, like this:
http://127.0.0.1:8000/static/profiles/i_vagin.jpg
But it must be:
http://127.0.0.1:8000/static/media/profiles/i_vagin.jpg
So how can I fix that?
Media files are not, by default, served during development. To enable media file serving, you need to add the following code in your urls.py file:
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)
Source: Django docs
Update
You'll also need to access images in your templates like this: {{ expert_photo.url }}