got error while setting default image in ImageField Django - 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'

Related

Django not rendering static image files localted in MEDIA directory

im relatively new to Django. I have an app where I specify MEDIA_URL and MEDIA_ROOT in settings.py file in project root. My pared down project structure looks like this:
/
../files
../files/media
../files/media/logo.png
../solid/settings.py
../solid/urls.py
/web/templates (contains all my HTML)
inside settings I have
MEDIA_ROOT = BASE_DIR / 'files'
MEDIA_URL = '/media/'
DEFAULT_FILE_STORAGE = BASE_DIR /'files'
in my template web/template/index.html I'm trying to reference it
<img src="{{% MEDIA_ROOT %}}/images/ourlogo.png" class="" alt="Logo" height="40">
In solid/urls.py I have:
urlpatterns = [
path('admin/', admin.site.urls),
path('',web_views.index,name="index"),
######################################################
path('login/',login_page,name="login"),
path('logout/',log_out,name="logot"),
path('register/',register,name="register"),
#######################################################
path('upload/',web_views.upload,name="upload"),
path('list/',web_views.list_uploads,name="list"),
path('details/<int:oid>', web_views.view_download,name='view_download'),
path('download/<str:filename>', web_views.download_file,name='download_file'),
#######################################################
path('paypal/', include("paypal.standard.ipn.urls")),
path('payment/',web_views.upgrade,name="payment"),
path('paypal-cancel/', PaypalCancelView.as_view(), name='paypal-cancel'),
path('paypal-return/', PaypalReturnView.as_view(), name='paypal-return'),
#######################################################
]+static('s/',document_root=settings.MEDIA_ROOT)
the image is not rendering.
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS =[
os.path.join(BASE_DIR,'project_name/static')
]
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
project_name/urls.py
add this two lines with urlspatterns
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
if want to get the image from database
<img src="{{ img.photo_2.url }}" alt="" class="img-fluid">
here "img" is the dictionary key name. photo_2 is the database field name. and to show the image you have put the .url after that.
static image
<link href="{% static 'img/favicon.png' %}" rel="icon">

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 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

How to show an ImageField in Django template

I have looked this questions from the stack overflow.
question 1
question 2 about showing an image field in a template and follow accordingly. But the image is not showing in the template although the image is properly uploaded to the folder.
models.py
class Book(models.Model):
book_thumbnail = models.ImageField(upload_to='images/%Y/%m/%d', blank=True, null=True)
views.py
def home(request):
book = Book.objects.all()
return render(request, 'books/books.html', context={'books': book})
template.html
<img class="group list-group-image" src="{{ books.book_thumbnail.url }}" width='240' alt="alt" />
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py
urlpatterns = [
path('books/', views.home),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
printing media root works for me.
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
print(MEDIA_ROOT)
Here is what i just edited in settings.py