Django image not loading Page not Found Error - html

I'm new to Django and I'm facing a problem of loading a static file (image). I got
127.0.0.1/:1707 GET http://127.0.0.1:8000/static/css/static/images/background/1.jpg 404 (Not Found)
I'm pretty sure that the problem is on the path but I can't understand where this /static/css/ comes from. Could you please help me?
My settings.py file:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'evillio/static')
]
My index.html file:
<!-- First Page with Picture and Search Starts -->
<section class="home-one home1-overlay **home1_bgi1**">
<div class="container">
<div class="row posr">
<div class="col-lg-12">
<div class="home_content">
<div class="home-text text-center">
<h2 class="fz55">Find Your Dream Home</h2>
<p class="fz18 color-white">From as low as $10 per day with limited time offer discounts.</p>
</div>
My CSS file:
home1_bgi1{
background-image: url('static/images/background/1.jpg');
-webkit-background-size: cover;
background-size: cover;
background-position: center center;
height: 960px;
When inspecting the page

Did you include {% load static %} at the top ??
For the latest version of Django, it doesn't use that in Setting.py:
`STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'evillio/static')
]`
Instead of this for Django 3.1 change code as bellow:
`STATICFILES_DIRS = [
BASE_DIR / "static",
'/var/www/static/',
]`
Read the documentation of Django 3.1, it has some code updated in the previous version of Django.
https://docs.djangoproject.com/en/3.1/howto/static-files/

Related

TemplateDoesNotExist at /blog/create/

When I click on create post it takes me to .../blog/create/ and I get this error: TemplateDoesNotExist at /blog/create/
base.html
<!DOCTYPE html>
<html lang*en>
<head>
<title>This is the Title</title>
{% include 'snippets/header.html' %}
</head>
<body>
<!-- Body -->
<style type="text/css">
.main{
min-height: 100vh;
height: 100%;
}
</style>
<div class="main">
{% block content %}
{% endblock content %}
</div>
{% include 'snippets/footer.html' %}
</body>
</html>
blog/Template/blog/create.html
{% extends 'base.html' %}
{% block content %}
<p>Create a new blog...</p>
{% endblock content %}
blog/urls.py
from django.urls import path
from blog.views import(
create_blog_view,
)
app_name = 'blog'
urlpatterns = [
path('create/', create_blog_view, name="create"),
]
main 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
from personal.views import (
home_screen_view,
)
from account.views import (
registration_view,
logout_view,
login_view,
account_view,
)
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_screen_view, name="home"),
path('register/', registration_view, name="register"),
path('blog/', include('blog.urls', 'blog')),
path('logout/', logout_view, name="logout"),
path('login/', login_view, name="login"),
path('account/', account_view, name="account"),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
blog/views.py
from django.shortcuts import render
from blog.models import BlogPost
def create_blog_view(request):
return render(request, "blog/create.html", {})
personal/Template/snippets/home.html
{% extends 'base.html' %}
{% block content %}
<style type="text/css">
#media (max-width: 768px) {
.right-column{
margin-left: 0px;
}
}
#media (min-width: 768px) {
.right-column{
margin-left: 20px;
}
}
.blog-post-container{
background-color: #fff;
margin-bottom: 20px;
width: 100%;
}
.create-post-bar{
background-color: #fff;
margin-bottom:20px;
}
.left-column{
padding:0px;
}
.right-column{
padding:0px;
}
</style>
<div class="container">
<div class="row">
<div class="create-post-bar d-lg-none col-lg-7 offset-lg-1">
Create post
</div>
<div class="left-column col-lg-7 offset-lg-1">
<div class="blog-post-container">
<p>Thingy</p>
</div>
<div class="blog-post-container">
<p>Thingy</p>
</div>
<div class="blog-post-container">
<p>Thingy</p>
</div>
</div>
<div class="right-column col-lg-3 d-lg-flex d-none flex-column">
<div class="create-post-bar">
<p>Stuff</p>
<p>Stuff</p>
<p>Stuff</p>
<a class="p-2 btn btn-outline-primary" href="{% url 'blog:create' %}">Create post</a>
</div>
</div>
</div>
</div>
{% endblock content %}
settings.py
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'personal',
'account',
'blog',
#Djangos apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'Templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
AUTH_USER_MODEL = 'account.Account'
WSGI_APPLICATION = 'mysite.wsgi.application'
...
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'media'),
]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn')
I was expecting it to redirect me to the new page but it shows an error.
With APP_DIRS enabled Django searches for templates inside each app /templates/ subfolder. Lowercase, plural.
You have Template - wrong case, missing s in the end. So yes, the template does not exist for Django because it cannot be found at any expected location.
Apparently your app doesn't look into blog's template folder. It only looks into personal
and account's template folders. You can check that in the attached picture under template-loader postmortem. It usually means that the app is not installed properly.
There are lots of reasons for such a thing, among them:
You might have located it in a wrong directory. The app must be at ./src/. It seems that it's not the case as the url.py is working properly.
It might be the case that you forgot to save settings.py after you added the blog app.
It might be your virtual environment. A restart and a migrate command might help.
Otherwise you might have changed the app's template directory somewhere.
You have, in your settings.py, the configuration
'DIRS': [os.path.join(BASE_DIR, 'Templates')],
so you need to have the Templates directory in your base directory, not inside each app, it should be
Template/blog/create.html
and not
blog/Template/blog/create.html

Dynamic URL routing is not working in django web application

A am working on a simple application, where trying to generate Dynamic URl and routing take place as per the ID in the url.
Dynamic value is getting populated in the URL, but it not performing action that needed.
prop_listings.html HTML Page:-
<div class="row text-secondary pb-2">
<div class="col-6">
<i class="fas fa-clock"></i> {{ listing.list_date | timesince }}
</div>
</div>
<hr>
More Info
</div>
</div>
</div>
URL.py in App Listings:-
from django.urls import path
from . import views
urlpatterns = [
path('',views.PropListings,name="prop_listings"),
path('<int:listing_id>', views.mlisting, name="morelisting"),
]
Views.py :-
def mlisting(request, listing_id):
# listingDetl = get_object_or_404(Listing, pk=listing_id)
listingDetl = Listing.objects.get(pk=listing_id)
print(listingDetl.username, listingDetl.address,listingDetl.city)
context = {
'listingDetails': listingDetl
}
return render(request,'listings/detail_listing.html', context)
URL.py in MainProject:-
urlpatterns = [
path('', include('static_pages.urls')),
path('user_account/', include('user_account.urls')),
path('listings/', include('listings.urls')),
path('feedback/', include('feedback.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Am trying to redirect the page from prop_listings.html to detail_listing.html, based on the below tag URL generated on listing.id
More Info
It's not working as expected on-click of above tag.
But when i did inspect on the same, URL is getting generated properly and when i click on the url, it will work as expected.
Inspect on the html page, URL populated
I looked into similar issue threads and tried to make changes, but not able to fix it.
Not getting what the issue and how to correct it.

Simple Background Image, Django unable to find image

Just wanting to make a simple multiple page website and I cant seem to get the background image to show on local host, Django just keeps saying Image not found. Can anyone help with this?? I want to drop vue in and do some fun stuff, but If I can't even get the images to show its going to be no fun at all.
The HTML File.
<body>
<section id="hero" class="d-flex align-items-center">
<div id="bg">
<div class="bg">
<img
src="{% static "media/ocean.jpg" %}"
class="bg1"
alt=""
/>
My View File
from django.shortcuts import render
# Create your views here.
def homepage(request):
return render(request, '/Users/mossboss/Dev/SimpleWS/apps/core/templates/core/base.html')
My Settings
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / 'static'
]
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

Django doesn't accept image submission, method and enctype included in form tag but browser console claims it is missing

I'm following along with a tutorial to build a Django project. Part of the project is being able to upload an image to the test cdn directory. This is what my form looks like currently:
<form method='POST' action="." enctype='multipart/form-data'> {% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>
The method and enctype are very clearly defined.
I've also set up my settings.py
STATIC_URL = '/static/'
LOCAL_STATIC_CDN_PATH = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn_test')
STATIC_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'staticfiles')
]
MEDIA_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, 'media')
MEDIA_URL = '/media/'
set up the files to be received in the view:
form = BlogPostModelForm(request.POST or None, request.FILES or None)
set up the model use ImageField:
image = models.ImageField(upload_to='image/', blank=True, null=True)
and the url patterns:
if settings.DEBUG:
# test mode
from django.conf.urls.static import static
# display images/files saved in the test cdn
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
But even with all this, the console informs me:
Form contains a file input, but is missing method=POST and enctype=multipart/form-data on the form. The file will not be sent.
This is the tutorial in case it helps https://www.youtube.com/watch?v=-oQvMHpKkms&list=PLM39hJgCef42hVok8ZRRE4LpLD-5bOxBh&index=20&t=13385s the part in question starts at 3:48:00.

how to show external media in template in django

Hi i'm currently new to Django and i'm trying to populate a product page.
I'm having problem with the img to show the image(which uses an image url online instead of a file) for example an img src="media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg"
The url already in my database with the text media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg
But when i tried to render it in template the image doesn't show
I tried to used the but it still not work
Any help would be appreciate!
My template
{% for discount in discounts|slice:":8" %}
<div class="col-md-3 product-men women_two">
<div class="product-googles-info googles">
<div class="men-pro-item">
<div class="men-thumb-item">
<img src="{{STATIC_URL}}{{discount.product_image}}" alt="" />
<div class="men-cart-pro">
<div class="inner-men-cart-pro">
Quick View
</div>
</div>
<span class="product-new-top">New</span>
</div>
<div class="item-info-product">
<div class="info-product-price">
<div class="grid_meta">
<div class="product_price">
<h4>
{{discount.product_name}}
</h4>
<div class="grid-price mt-2">
<span class="money">{{discount.product_old_price}}</span>
</div>
</div>
<div>
<h3>{{discount.product_sit}}</h3>
</div>
<div><h2 style="color: red;">Only {{discount.product_price}}!</h2></div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
{% endfor %}
EDIT
Seems like the image src trying to get is "http://127.0.0.1:8000/media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg" which i don't want "http://127.0.0.1:8000/" in the link. Is there a way to remove this when using {{discount.product_image}} tag ?
Main project urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('frontend.urls')),
]
frontend app urls.py:
from django.urls import path
from .import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'frontend'
urlpatterns = [
#index
path('',views.index, name='index')
]
Try using .url like this.
<img src="{{ discount.product_image.url }}" alt=""/>
Also add the MEDIA and STATIC url to your project url patterns.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URL pattern goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
EDIT:
From the discussion in chat, I understood that I had misunderstood your problem first. The images are external and not in your db, you are just storing the URL to the images. And you are using a TextField not ImageField. I assumed ImageField previously. So, all you have to do is to replace {{STATIC_URL}} from in front of the actual URL and put http:// there. The reason behind this is, as the src is missing http:// it's assumed the image to be in the same host domain. So it goes to http://127.0.0.1/your_url.
<img src="http://{{ discount.product_image }}" alt=""/>