I am stuck on this 404 error
When I try to find what the error is using inspection I get this
My settings code:
STATIC_URL = '/static/'
MEDIA_URL = '/images/'
STATICFILES_DIR =[
os.path.join(BASE_DIR, 'static')
]
How i refer to my image in the html file
<img src="{% static 'images/logo.png' %}" alt="Image">
My urls file:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('amitians.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I have a static folder inside which i have an images folder
On my inspection page the file type is shown as text/html though its clearly a .png. Not sure if its related but here
and my error as shown in the command prompt geos like this:
Quit the server with CTRL-BREAK.
[12/Dec/2020 13:44:45] "GET / HTTP/1.1" 200 2616
[12/Dec/2020 13:44:45] "GET /static/images/logo.png HTTP/1.1" 404 1772
I've tried many solutions on stackoverflow but cant seem to get it working
I've tried using my image file directly in the statics folder too.
Would be GLAD if someone cud help out!
try this add and static directory in your apps and in each static directory add another directory with the app name like below:
├───Project_Directory
│ ├───app_name
│ │ ├───migrations
│ │ ├───static
│ │ │ └───app_name
│ │ │ ├───css
│ │ │ └───images
now in your template use:
<img src="{% static 'app_name/images/logo.png' %}" alt="Image">
and see if that works
I think you are using jinja format inside the global jinja format. Check to whether you have loaded static as baseUrl;
{% static "images" as baseUrl %}
just add like this it will solve your problem :
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/images/'
STATICFILES_DIR =[
os.path.join(BASE_DIR, 'static')
]
In your html file
<img class="card-img-top" src={% static 'images/background.jpg' %}>
I have followed many of the answers provided here but I still cannot open the file.
I have an text file that I would like to render on my home.html. I rewrote my views.py as suggested:
def homepage_view(request):
module_dir = os.path.dirname(__file__)
file_path = os.path.join(module_dir, 'my_text.txt')
data_file = open(file_path, 'r')
data = data_file.read()
context = {'intro' : data}
return render(request, 'home.html', context)
Here is my home.html. The html includes: from . import forms, from . import views:
<div class="intro">
{% block intro %}
{{block.super }}
{{intro}}
{% endblock %}
</div>
My app/urls.py is:
from page import views
app_name = 'page'
urlpatterns = [
path('home/', views.homepage_view, name='homepage_view'),
path('upload/', views.csvUpload, name='csv_upload'),
path('zip/', views.zipUser_view, name = 'zipUser_view'),
path('results/', views.results_view, name='results_view'),
path('ky_outline/', views.display_ky_image, name = 'ky_image'),
]
My structure is:
myproject/
__pycache__
__init__.py
settings.py
urls.py
wsgi.py
my/app ('page')
__pycache__
migrations
static
page
css
style.css
images
media
my_text.txt
static and media settings are:
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = [],
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
What am I missing or have I looked at this too long?
In views, try to put the path manually instead of use os, if it's work then is problem of how you give the path to open()
I followed the steps indicated in the tutorials but the image is still not seen. It finds it but it does not show it: "GET /static/imagenes/triste.png HTTP / 1.1" 404 1782. The images are in static/imagenes.
{% load static %}
<img src= "{% static 'imagenes/feliz.png' %}" alt="hola" >
settings.py
STATIC_URL = '/static/'
STATICFILES_DIR = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR,"static")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('configuracionSecreta/', include('apps.configuracion.urls')),
path('dialogo/', include('apps.dialogo.urls')),
path('posicionamiento/', include('apps.dialogo_pos.urls')),
path('resultados/', include('apps.resultados_test.urls')),
path('', include('apps.test_datos.urls')),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
├───.vscode
├───apps
│ ├───configuracion
│ ├───dialogo
│ ├───dialogo_pos
│ ├───resultados_test
│ └───test_datos
├───media
├───static
│ ├───bower_components
│ ├───imagenes
├───templates
│ ├───base
│ ├───configuracion
│ ├───dialogo
│ ├───dialogo_pos
│ ├───resultados_test
│ └───test_datos
└───tfg_project
#dialogo_pos/urls.py
from django.urls import path
from apps.dialogo_pos.views import *
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', dialogoPosIni.as_view(), name='inicio'),
path('final', dialogoPosFin.as_view(), name='fin')
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I am trying to do an application for a blog by Django, but the top page (post_list.html) is not displayed.
The following error message will be displayed.
TemplateDoesNotExist at /
blogapp3/post_list.html
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.11.4
Exception Type: TemplateDoesNotExist
Exception Value:
blogapp3/post_list.html
Exception Location: F:\01_pro\kaso3\lib\site-packages\django\template\loader.py in select_template, line 53
Python Executable: F:\01_pro\kaso3\Scripts\python.exe
Python Version: 3.6.2
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.filesystem.Loader: F:\01_pro\blogpro3\blogapp3\templates\blog\blogapp3\post_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: F:\01_pro\kaso3\lib\site-packages\django\contrib\admin\templates\blogapp3\post_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: F:\01_pro\kaso3\lib\site-packages\django\contrib\auth\templates\blogapp3\post_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: F:\01_pro\blogpro3\blogapp3\templates\blogapp3\post_list.html (Source does not exist)
I had been pointed out that the file structure is wrong from other websites, but I think this file doesn't seem to be strange. File structure is as follows.
F:\01_PRO\BLOGPRO3
│ db.sqlite3
│ manage.py
│
├─blogapp3
│ │ admin.py
│ │ apps.py
│ │ forms.py
│ │ models.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ __init__.py
│ │
│ ├─migrations
│ │ │ 0001_initial.py
│ │ | 0002_auto_20170905_1930.py
│ │ └─ __init__.py
│ │
│ │
│ ├─static
│ │ ├─css
│ │ │ blog.css
│ │ │
│ │ └─js
│ │
│ └─templates
│ ├─blog
│ │ about.html
│ │ base.html
│ │ comment_form.html
│ │ post_confirm_delete.html
│ │ post_detail.html
│ │ post_draft_list.html
│ │ post_form.html
│ │ post_list.html
│ │
│ └─registration
│ login.html
│
│
└─blogpro3
settings.py
urls.py
wsgi.py
__init__.py
Below, I display urls.py, views.py, settings.py in order to solve this issue.
blogpro3/urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views
urlpatterns = [
url(r'^admin/',admin.site.urls),
url(r'',include('blogapp3.urls')),
url(r'^accounts/login/$', views.login, name='login'),
url(r'^accounts/logout/$', views.logout, name='logout', kwargs={'next_page': '/'}),
]
blogapp3/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.PostListView.as_view(), name='post_list'),
url(r'^about/$',views.AboutView.as_view(),name='about'),
url(r'^post/(?P<pk>\d+)$',views.PostDetailView.as_view(),name='post_detail'),
url(r'^post/new/$',views.CreatePostView.as_view(),name='post_new'),
url(r'^post/(?P<pk>\d+)/edit/$',views.PostUpdateView.as_view(),name='post_edit'),
url(r'^post/(?P<pk>\d+)/remove/$',views.PostDetailView.as_view(),name='post_remove'),
url(r'^drafts/$',views.DraftListView.as_view(),name='post_draft_list'),
url(r'^post/(?P<pk>\d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'),
url(r'^comment/(?P<pk>\d+)/approve/$',views.comment_approve,name='comment_approve'),
url(r'^comment/(?P<pk>\d+)/remove/$',views.comment_remove,name='comment_remove'),
url(r'^post/(?P<pk>\d+)/publish/$',views.post_publish,name='post_publish'),
]
views.py
from django.shortcuts import render,get_object_or_404,redirect
from django.contrib.auth.decorators import login_required
from blogapp3.models import Post,Comment
from django.utils import timezone
from blogapp3.forms import PostForm,CommentForm
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
class PostDetailView(DetailView):
model = Post
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
class PostUpdateView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
class PostDleteView(LoginRequiredMixin,DeleteView):
model = Post
success_url = reverse_lazy('post_list')
class DraftListView(LoginRequiredMixin,ListView):
login_url = '/login/'
redirect_field_name = 'blog/post_list.html'
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__isnull=True).order_by('created_date')
##################################
##################################
#login_required
def post_publish(request,pk):
post = get_object_or_404(Post,pk=pk)
post.publish()
return redirect('post_detail',pk=pk)
#login_required
def add_comment_to_post(request,pk):
post = get_object_or_404(Post,pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail',pk=post.pk)
else:
form = CommentForm()
return render(request,'blog/comment_form.html',{'form':form})
#login_required
def comment_approve(request,pk):
comment = get_object_or_404(Comment,pk=pk)
comment.approve()
return redirect('post_detail',pk=comment.post.pk)
#login_required
def comment_remove(request,pk):
comment = get_object_or_404(Comment,pk=pk)
post_pk = comment.post.pk
comment.delete()
return redirect('post_detail',pk=post_pk)
settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIRS = os.path.join(BASE_DIR,'blogapp3/templates/blog')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blogapp3.apps.BlogappConfig',
]
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 = 'blogpro3.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIRS,],
'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',
],
},
},
]
WSGI_APPLICATION = 'blogpro3.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'Static')
LOGIN_REDIRECT_URL = '/'
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),)
What I am paying attention to is the following part in the error message.
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.filesystem.Loader: F:\01_pro\blogpro3\blogapp3\templates\blog\blogapp3\post_list.html (Source does not exist)
The above path should be correct for following path.
F:\01_pro\blogpro3\blogapp3\templates\blog\post_list.html
However, I don't know how to fix above path.
I am glad if you tell me how to solve this issue.
Your file structure confirms exactly what the error says: there is no templates directory named "blogapp3", so there is no template named "blogapp3/post_list.html".
You should move your templates into the "blogapp3" directory.
I want to have global static files and templates for all my apps. My apps also will have templates and static files It will look something like this:
I am loading my global files like these but it is not working.
{% load staticfiles %}
href="{% static 'bootstrap/css/bootstrap.min.css' %}"
and I get:
"NetworkError: 500 Internal Server Error - http://localhost:8000/static/bootstrap/css/bootstrap.min.css"
By the way I can access to my apps static but not the global, I debug the STATIC_ROOT and PROJECT_ROOT and they seem good.
PROJECT_ROOT ='C:\\webpages\\client_portal\\client_portal'
projectname]/ <- project root
├── [projectname]/ <- Django root
│ ├── __init__.py
│ ├── settings/
│ ├── urls.py
│ └── wsgi.py
├── apps/
│ └── __init__.py
│
├── manage.py
│
├── static/
│ └── GLOBAL STATIC FILES
└── templates/
└── GLOBAL TEMPLATES
My settings.py looks like this:
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, '/static')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, '/static'),
)
STATIC_ROOT and STATICFILES_DIRS should not be the same. Create a different directory, eg staticfiles, to store your development static files and use that in STATICFILES_DIRS instead.
I think your problem is that you have an unneeded forward slash in STATICFILES_DIRS. So change this:
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, '/static'),
)
to this:
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
Hope it helps, it worked for me in Django 2.0, without the need of using PROJECT_ROOT neither STATIC_ROOT.