I'm making a website and the static files are not loading,
when i try to accsess static files with localhost:8000/static/image.png it shows this:
Page Not found (404)'image.png' could not be found
and the index page is showing the image that displays when the image couldn't be found
files:
VoicesOnTheSpectrum
VoicesOnTheSpectrum
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
vots
migrations
static
image.png
logo.png
style.css
votstop.png
templates
vots
base.html
index.html
__init__.py
admin.py
apps.py
models.py
tests.py
urls.py
views.py
manage.py
settings.py:
from pathlib import Path
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, "vots", "templates")
SECRET_KEY = 'secret'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_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 = 'VoicesOnTheSpectrum.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'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 = 'VoicesOnTheSpectrum.wsgi.application'
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static')]
# STATIC_ROOT = os.path.join(BASE_DIR, "static")
index:
{% extends "vots/base.html" %}
{% load static %}
{% block content %}
<div role="img">
<img src="{% static 'votstop.png' %}">
</div>
{% endblock %}
base:
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}Voices On The Spectrum</title>
<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}">
</head>
<body>
<div class="navbar">
</div>
<div class="body">
{% block content %}
{% endblock %}
</div>
<div class="footer">
<p>Copyright © {% now "Y" %} Voices on the Spectrum - All Rights Reserved.</p>
<div class="insta">
<img src="{% static 'image.png' %}" alt="Instagram">
</div>
</div>
</body>
</html>
You need to add the view(s) to your urlpatterns to serve static (and media) files:
# VoicesOnTheSpectrum/urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# … other urls patterns …
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My Answer
just needed to add my app to installed apps
INSTALLED_APPS = [
'vots',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
Related
I have create a small project , where i am stuck at one point
Issue : not able to get images dynamically and display in template
i.image.url -> at this line in html images are not coming from folder media
when i runserver the media folder is not getting created and images are not copied from pics to media folder
seetings.py
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = []
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'web_components')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL='/media/pics/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'LEARN_FROM_TELUSKO',
]
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 = 'PROJECT.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'Template')],
'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',
'django.template.context_processors.media',
],
},
},
]
urls.py
urlpatterns = [
path('', include('LEARN_FROM_TELUSKO.urls')),
path('admin/', admin.site.urls)
]
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
class courses(models.Model):
name = models.CharField(max_length=100)
price = models.IntegerField()
image = models.ImageField(upload_to='pics', height_field=None, width_field=None, max_length=None)
views.py
def index(request):
dest = courses.objects.all()
return render(request,'index.html',{'getdetails':dest})
template
{% for i in getdetails %}
<div class="col-xl-3 col-lg-3 col-md-6 col-sm-12">
<div class="product-box">
<i>
<img src="{{ i.image.url }}"/>
</i>
<h3>{{ i.name }} </h3>
<span>{{ i.price }}</span>
</div>
</div>
{% endfor %}
Project structure:
I uploaded files to 127.0.0.1/8000/admin:
Here they are mentioned in the db
The title is pretty much self explanatory. I did put some images in the static/rakunai folder and added the dirs etc, the whole shebang. I still can't get to display it. I am using docker. Python 3.8 was used and the newest django version was used.
The settings.py:
```
"""
Django settings for rakunai project.
Generated by 'django-admin startproject' using Django 2.2.12.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# 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',
]
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 = 'rakunai.urls'
STYLESHEETS='/stylesheets/'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['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',
],
},
},
]
WSGI_APPLICATION = 'rakunai.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'db',
'PORT': 5432,
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/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/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = ['rakunai']
```
templates/aboutus.html:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!--todo:fix this-->
<link rel="stylesheet" href="{% static 'styles.css' %}" type="text/css">
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<title>Index page</title>
...
<div class="row rowteams align-tems-center">
<div class="col-xs-12 col-sm-6 padding-0">
<img class="teamimages" src="{% static 'rakunai/img.jpg' %}">
</div>
<div class="col-sm-6 padding-0 skobeloff-bg linen-text">
<h2>
Simonas Bansevičius
</h2>
<h5>
CEO
</h5>
</div>
</div>
views.py:
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
def about(request):
return render(request, 'about.html')
def css(request):
return render(request, 'styles.css')
Urlpaterls:
from rakunai.views import index as home
from rakunai.views import about as details
from rakunai.views import css
urlpatterns = [
path('admin/', admin.site.urls),
path('', home),
path('about', details),
]
Any type of feedback is highly appreciated.
BASE_DIR = os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__))))
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'rakunai')]
MEDIA_URL = '/media/'
in settings.py
<img class="teamimages" src="/static/media/img.jpg" %}">
in html file
put images in rakunai/media/
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
add this in urls.py
You have not included the static urls and media urls in your urls.py.
Including them would look something like this:-
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from rakunai.views import index as home
from rakunai.views import about as details
urlpatterns = [
path('admin/', admin.site.urls),
path('', home),
path('about', details),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I have recently started a blog using django from Corey Schaeffer's tutorial. I am stuck at part 6: User Registration, the feedback says template does not exist at users/register.html at line 19.
I have attempted to send the directory in settings to the absolute location of my templates, but it keeps responding with the same feedback.
I must be incorrectly referencing in my register.html or settings. Or even worse, a clerical/technical error!
My settings file
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'lzjtwkmz)f5nmj+#^vmiu^2rk+!24f1if72aq81+ny=wiiwn+g'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'blog.apps.BlogConfig',
'users.apps.UsersConfig',
'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 = 'django_project2.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['C:/Users/sabay/django_project2/blog/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',
],
},
},
]
WSGI_APPLICATION = 'django_project2.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
my register.html file
{% extends "blog/base.html" %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Join Today</legend>
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="#">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
my urls.py
from django.contrib import admin
from django.urls import path, include
from users import views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register, name='register'),
path('', include('blog.urls')),
]
I expect the output to result in webpage of the register page however the actual result leads to me a 'TemplateDoesNotExist at /register/'.
Any help would be appreciated, and sorry if the code text is horrendous to look at, this is my first time using stackover flow.
Try without the / in front of register, 'register/' instead of '/register/'
I`m trying to extend one html file from other, but it simply shows me only base.html result.
Here is my project folders:
-diploma
-catalogue
-migrations
-templates
-catalogue
base.html
header.html
_init__.py
admin.py
apps.py
models.py
tests.py
urls.py
views.py
-diploma
__init__.py
settings.py
urls.py
wsgi.py
settings.py
...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'catalogue',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
...
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',
],
},
},
]
urls.py
from django.conf.urls import url
from catalogue import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
views.py
from django.shortcuts import render
def index(request):
return render(request, 'catalogue/base.html')
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
header.html
{% extends 'catalogue/base.html' %}
{% block content %}
<h1>Hello</h1>
{% endblock %}
Really, trying to find the issue, but can`t figure out. Only effect cghanges made in base.html
Try putting:
{% extends 'base.html' %}
instead of the whole path
I just installed Django AllAuth to my project, but cant find default login or signup page.
1) I logged out from admin panel, but still didn't find it.
2) Added signup.html template, but nothing
Picture of error in localhost/accounts http://prntscr.com/9oyu00
Here's my code:
settings.py
# 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',
'profiles',
'contact',
'crispy_forms',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'src.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',
],
},
},
]
WSGI_APPLICATION = 'src.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/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.9/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.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media")
STATICFILES_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "static", "static"),
)
# Location of templates
CRISPY_TEMPLATE_PACK = 'bootstrap3'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
SITE_ID = 1
LOGIN_URL = '/accounts/login'
LOGIN_REDIRECT = '/'
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
ACCOUNT_CONFIRM_EMAIL_ON_GET = False
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = LOGIN_URL
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3
ACCOUNT_EMAIL_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = None
ACCOUNT_EMAIL_SUBJECT_PREFIX = "My subject: "
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http"
ACCOUNT_LOGOUT_ON_GET = False
ACCOUNT_LOGOUT_REDIRECT_URL = "/"
ACCOUNT_SIGNUP_FORM_CLASS = None
ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_USERNAME_FIELD = "username"
ACCOUNT_USER_MODEL_EMAIL_FIELD = "email"
ACCOUNT_USERNAME_MIN_LENGTH = 5
ACCOUNT_USERNAME_BLACKLIST = []
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_PASSWORD_INPUT_RENDER_VALUE = False
ACCOUNT_PASSWORD_MIN_LENGTH = 6
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from contact import views
urlpatterns = [
url(r'^$', 'profiles.views.home', name='home'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^accounts/', include('allauth.urls')),
url(r'^admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
signup.html
{% extends "account/base.html" %}
{% load crispy_forms_tags %}
{% load i18n %}
{% block head_title %}{% trans "Signup" %}{% endblock %}
{% block content %}
<h1>{% trans "Sign Up" %}</h1>
<p>{% blocktrans %}Already have an account? Then please sign in.{% endblocktrans %}</p>
<form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}">
{% csrf_token %}
{{ form|crispy }}
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
{% endif %}
<button class='btn btn-default' type="submit">{% trans "Sign Up" %} »</button>
</form>
{% endblock %}
I had the same problem. The source of it all was that I had already defined a base.html file without a 'block content' block. You need the following structure inside the body of your base.html file:
<body>
{% block body %}
{% block content %}
{% endblock content %}
{% endblock body %}
</body>
I used this source to find a suitable example, but it's not very helpful other than that. This other page was a bit better though.
Because you are requesting only the /accounts/ and if you see closely to your debugger (the screen) there is no URL for this (pattern ^accounts/ ^ ^$).
Your login & sing up page is located on /accounts/login/ and /accounts/singup/.
About editing default templates I am not able to help you with it (never used the AllAuth package) so hope someone skilled will help you.