Django : Media Images not displayed in templates - django

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

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 Files not displayed in templates

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'),
)

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 Static Image Showing then Not Showing, Views Share Base Html File Where Static Logo image is

My logo which is in my djangoprojectdir/static/media/ folder is showing on my homepage but in none of my other views. I dont know why it doesnt show up on other pages it shares the same base.html file for the navigation bar and header. Currently hosted website in production on digital ocean, nginx, gunicorn. I am just trying to serve static files in production debug off for small project with no database. I have already collected static. The image only works on my IndexView. My other static image files relating to my objects seem to be rendering fine. I have been exhaustively trying to figure this out.
The Image code out of the base.html that is problematic is:
<a class="navbar-brand" href="{% url 'maps:index' %}"><img src="static/media/Dirt logo3.png" hieght="5" class="img-fluid" alt="Responsive image"> </a>
I have tried mapping with {{ MEDIA_URL }}/Dirt logo3.png and {{ STATIC_URL }} to no avail, Hardcoded would be fine if it worked.
from base.html
#bootstrap stuff here#
{% load static from staticfiles %}
<a class="navbar-brand" href="{% url 'maps:index' %}"><img src="static/media/Dirt logo3.png" hieght="5" class="img-fluid" alt="Responsive image"> </a>
{% block body %}
{% endblock %}
from settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'mysite', 'maps', 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'mysite', 'maps', 'static', 'media')
MEDIA_URL = 'static/media/'
MEDIA_DIR = os.path.join(BASE_DIR, "")
Views.py
# works on IndexView but not any other view
class IndexView(generic.ListView):
template_name = 'maps/index.html'
paginate_by = 20
def get_queryset(self):
return Location.objects.all()
context_object_name = 'location'
class NeeddirtView(generic.ListView):
template_name = 'maps/needdirt.html'
paginate_by = 20
def get_queryset(self):
return Location.objects.all()
context_object_name = 'location'
from maps/urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'maps'
urlpatterns = [
# /maps/
path('', views.IndexView.as_view(), name='index'),
# /maps/71/
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('register/', views.UserFormView.as_view(), name='register'),
path('login/', views.LoginView.as_view(), name='login'),
path('logout/', views.LogoutView.as_view(), name='logout'),
# /maps/companies/
path('companies/', views.CompView.as_view(), name='comp'),
# /maps/equipment/
path('equipment/', views.EquipView.as_view(), name='equip'),
#maps/
path('equipment/<int:pk>/', views.EquipdetView.as_view(), name='equipdet'),
path('location/add/', views.LocationCreate.as_view(), name='location-add'),
path('location/<int:pk>/', views.LocationCreate.as_view(), name='location-update'),
path('location/<int:pk>/delete/', views.LocationDelete.as_view(), name='location-delete'),
path('equipment/add/', views.EquipCreate.as_view(), name='equipment-add'),
path('equipment/<int:pk>/', views.EquipCreate.as_view(), name='equipment-update'),
path('equipment/<int:pk>/delete/', views.EquipDelete.as_view(), name='equipment-delete'),
path('quarry/', views.QuarryView.as_view(), name='quarry'),
path('quarry/<int:pk>/', views.QuarrydetView.as_view(), name='quarrydet'),
path('quarry/add/', views.QuarryCreate.as_view(), name='quarry-add'),
path('quarry/<int:pk>/', views.QuarryCreate.as_view(), name='quarry-update'),
path('quarry/<int:pk>/delete/', views.QuarryDelete.as_view(), name='quarry-delete'),
path('search/', views.search, name='search'),
path('test/', views.TestView.as_view(), name='test'),
path('needdirt/', views.NeeddirtView.as_view(), name='needdirt'),
path('havedirt/', views.HavedirtView.as_view(), name='havedirt'),
path('about/', views.AboutView.as_view(), name='about'),
]
from urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', include('maps.urls')),
path('admin/', admin.site.urls),
path('maps/', include('maps.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Any help is greatly appreciated.
The problem is most likely due to your relative path. Try:
<img src="/static/media/Dirt logo3.png"... />
Note leading slash which makes it relative to root.
I do not like spaces in filenames, so I would change that, too.

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.