This question already has an answer here:
how to upload file in a specific address using django admin panel?
(1 answer)
Closed 4 years ago.
I want to show the uploaded image in the django templates,but it was not showing any image,i have successfully uploaded and saved it,how can i fix this problem,could anyone please explain or a sample demo on how we have to configure our settings.py to display the image in templates?
my settings.py:
LOGIN_URL='/login'
STATIC_URL = '/static/'
LOGIN_REDIRECT_URL = '/home'
LOGOUT_REDIRECT_URL='/accounts'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
my models.py:
class Images(models.Model):
user_id=models.ForeignKey(User,on_delete=models.CASCADE,null=True)
image=models.FileField(upload_to='home')
And the Image tag i was using to display it is
<img src="{{ obj.image.url }}" class="img-circle" height="65" width="65" alt="Avatar">
my urls.py:
from django.urls import path
from . import views
from . models import FavBooks
from django.conf import settings
from django.conf.urls.static import static
app_name='home'
urlpatterns=[
path('',views.HomeView,name='home'),
path('addBooks/',views.addBooks,name='addBooks'),
path('uploadpic/',views.uploadPic,name='uploadPic'),
path('myBooks/',views.BooksView.as_view(),name='myBooks'),
path('<int:pk>/', views.BookDetailsView.as_view(), name='myBooks'),
path('search/', views.SearchedBooks, name='searchedBooks'),
path('favoriteAjax/', views.favorite_ajax, name='favoriteAjax'),
path('removefavoriteAjax/', views.removefavorite_ajax, name='removefavoriteAjax'),
path('wishList/',views.WishlistView.as_view(),name='wishList'),
path('deletebook/', views.deleteBook, name='deleteBook'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
add this in urls.py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Related
This question already has answers here:
Why does DEBUG=False setting make my django Static Files Access fail?
(20 answers)
Closed 5 months ago.
http://127.0.0.1:8000/static/apis/icons/random-svgrepo-com.svg gives me error 404 not found.
settings.py
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
STATICFILES_DIR = [
os.path.join(BASE_DIR, 'staticfiles/'),
]
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
template.html
{% load static %}
<img src="{% static 'apis/icons/random-svg.svg' %}">
root urls.py
from django.conf.urls.static import static
from django.conf import settings
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Work directory:
I am running ./manage.py collectstatic, and then run the server. But it doesn't show me my image.
My questions are:
Difference between STATICFILES_DIR and STATICFILES_DIRS
What I am doing wrong? Why my static files doesn't appear to work fine?
Thanks!
Changed my root urls.py to:
from django.conf import settings
from django.views.static import serve
urlpatterns += [
re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
re_path(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT})
]
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}),
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
Ok, I have a Django 1.10 project. The relevant settings look like this:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = BASE_DIR + "/media/"
MEDIA_URL = '/media/'
I'm working locally, I can upload images correctly. But when I try to access the image on a template using {{ image.image.url }}, I get a 404. In the terminal I can see this:
[06/Sep/2016 18:13:43] "GET /media/folder/uploaded_image.jpg HTTP/1.1" 404 4900
But if I look into my folder, the file is there, correctly uploaded by django.
Try using os.path.join, like this:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
You probably also need to update your urls.py with this:
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
if settings.DEBUG is True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I have correctly set the settings for media in settings.py as:-
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
and also specified the correct url settings
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'^media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
Whenever i upload an image through admin..the image gets uploaded in my media folder but i can't see it when i run my development server...it shows a page not found (404) error...
I think the problem is due to some permissions of uploaded files which is why django shows a 404 page when trying to access them..if someone knows about this please help
Please suggest me a solution
Thank you!
Try this:
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)
Relevant url:
https://docs.djangoproject.com/en/1.7/howto/static-files/#serving-files-uploaded-by-a-user-during-development
Do this
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
# your urls here.
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)