Django 3.1 media prefix not showing on urls - django

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

Related

got error while setting default image in ImageField Django

my model have an imagefield which stores the image for post . I want to add default image to that in case if not is not uploaded.But I am getting error The 'title_image' attribute has no file associated with it. If I upload image then its working fine.
Models.py
class Post(models.Model):
title_image = models.ImageField(
upload_to='Images/PostTitleImages/',
max_length=None,
default = 'Images/Image_not_found.jpg',
blank = True,
null = True)
home.html
<img src="{{post.title_image.url}}" height="350px"/>
Settings.py
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static/'),
]
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('MainSite.urls'), name = "Main"),
path('account/',include('account.urls'), name = 'Accounts')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
what I am doing wrong here I checked the file is in this directory /media/Images/PostTitleImages/
In case of media you need to include the media tag in your template like so:
# template
<img src="{{ media_url }}{{ post.title_image.url }}>
and in your settings add the context processor
# settings.py
'django.template.context_processors.media'

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 : 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 Template Image not displaying even with media url and media root

Static images are showing properly. The files in the media folder are not displaying in html. I tried setting up media_url in various ways but in vain. I uploaded the image via django admin panel. The name of product is showing fine. The img.url shows /media/p2.jpg
models.py
class Product(models.Model):
name = CharField(("Name"),max_length=256,blank=False)
title_img = models.ImageField(null=True, blank=True)
settings.py
PROJECT_ROOT = (os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(PROJECT_ROOT), "media_root")
urls.py
urlpatterns = [
path('', ProductList.as_view() , name="product"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
template.html
{{p.name}}
<img src="{{p.title_img.url}}">
the name is displayed while image is not displayed. In console, I get
"GET /media/p2.jpg HTTP/1.1" 404 2690
I changed some settings and was able to resolve it. Probably the mistake was that I was changing project_root/products/urls.py instead or project_root/urls.py. Overall changes I did:
In main urls.py, added these
urlpatterns = [
path('', ProductList.as_view() , name="product"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Changed settings.py
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media/')
MEDIA_URL = '/media/'
As per the documentation: https://docs.djangoproject.com/en/3.1/howto/static-files/#serving-static-files-during-development and https://docs.djangoproject.com/en/3.1/howto/static-files/#serving-files-uploaded-by-a-user-during-development
it should be used only for development purposes,
settings.DEBUG must be set to True,
it works only if the url is local
in your case, 1 and 3 seams ok but is your DEBUG setting set to True?
As per the documentation: https://docs.djangoproject.com/fr/3.1/ref/contrib/staticfiles/#runserver, you can runserver with argument --insecure so you can still serve static files or media file with DEBUG set to False.

django-photologue thumbnails not loading

I am trying to use django-photologue, I installed it and did mentioned settings.
I have a model Blog as follows:
class Blog(models.Model):
title = models.CharField(max_length=150)
thumbnail = models.ForeignKey(Photo, related_name='blogs')
I am able to add images to blog objects, however I do not see the thumbnail in my admin interface (clicking on it basically opens base.html stored in templates folder which I simply copied from example_project, this base.html is not important for me, however seeing this thumbnail could be interesting):
NOTE: I guess my MEDIA_ROOT and MDIA_URL properties are wrong, I am not sure what I should be writing there. I get
GET http://127.0.0.1:8000/photologue/photologue/photos/cache/dog_1_admin_thumbnail.jpg 404 (Not Found)
for
MEDIA_ROOT = os.path.join(BASE_DIR, 'photologue', )
MEDIA_URL = '/photologue/'
error, on my console.
My folder structure:
The thumbnails part of the question is fixed by doing following settings:
In my urls.py file I had to
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
#all urls
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And in my settings.py file I added:
STATIC_ROOT = os.path.join(BASE_DIR, 'public', 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'public', 'media')
MEDIA_URL = '/media/'