Django Template Syntax Error - Django Webpack - django

I'm working on a django webpack bundle. I got a ready template on github. I made a few changes on it. I prepare for future use according to my own file hierarchy. But I am having a problem with template synxtax. First, there is base.html in my project. Thanks to this page, the background of the pages that I will create in the future is formed. Some files were imported in base.html. These are implemented using render_bundle and static tags. I created a new page to be rendered in django. Likewise, I want to import assets/js/table.js and assets/scss/table.scss files on this page separately from other pages. but I am getting a template syntax error. Where do you think I'm making a mistake?
i got this error
base.html
{% load render_bundle from webpack_loader %}
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{% block meta %}
{% endblock meta %}
<title>
{% block title %}
{% endblock %}
</title>
<!-- You should added this tags for production files !!! -->
{% render_bundle 'app' 'css' %}
{% render_bundle 'myapp' 'css' %}
<link href="/media/favicon.png" rel=icon>
{% block head %}
{% endblock %}
</head>
<body>
{% include "navbar.html" %}
<!-- Content -->
{% block body %}
{% endblock %}
<!-- Start -->
{% if settings.DEBUG and settings.WEBPACK_LIVE_SERVER %}
<!-- You should added this tags for development files -->
<script src="{{ settings.WEBPACK_LIVE_SERVER_CONFIG.ADDRESS }}/vendor.bundle.js"></script>
<script src="{{ settings.WEBPACK_LIVE_SERVER_CONFIG.ADDRESS }}/app.bundle.js"></script>
<script src="{{ settings.WEBPACK_LIVE_SERVER_CONFIG.ADDRESS }}/myapp.bundle.js"></script>
{% else %}
<!-- You should added this tags for production files !!! -->
{% render_bundle 'vendor' 'js' %}
{% render_bundle 'app' 'js' %}
{% render_bundle 'myapp' 'js' %}
{% endif %}
<!-- End -->
{% block scriptblock %}
{% endblock scriptblock %}
<!-- Your static import javascript modules -->
<script src="{% static 'new.js' %}"></script>
</body>
</html>
table.html
{% extends "base.html" %}
{% block title %}
Table Test Page
{% endblock title %}
{% block head %}
{% render_bundle 'table' 'css' %}
{% endblock head %}
{% block body %}
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsa, sed.</p>
{% endblock body %}
<!-- Start -->
<!-- Import JS Files for Development and Production -->
{% if settings.DEBUG and settings.WEBPACK_LIVE_SERVER %}
<script src="{{ settings.WEBPACK_LIVE_SERVER_CONFIG.ADDRESS }}/table.bundle.js"></script>
{% else %}
<!-- You should added this tags for production files !!! -->
{% render_bundle 'table' 'js' %}
{% endif %}
<!-- End -->
webpack.common.js
const path = require('path')
var HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: {
app: "./assets/js/app.js",
vendor: "./assets/js/vendor.js",
myapp: "./assets/js/myapp.js",
table: "./assets/js/table.js",
},
module: {
rules: [{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(svg|png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath: "imgs"
}
}
}
]
}
};
webpack.dev.js
const path = require("path");
const common = require("./webpack.common");
const { merge } = require("webpack-merge");
const { CleanWebpackPlugin }= require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const BundleTracker = require('webpack-bundle-tracker');
module.exports = merge(common, {
mode: "development",
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "./assets/bundles/dev"),
publicPath: "/static/dev/",
},
plugins: [
new MiniCssExtractPlugin({ filename: "[name].bundle.css" }),
new CleanWebpackPlugin(),
new BundleTracker({path: __dirname, filename: './assets/bundles/dev/stats.json'})
],
module: {
rules: [
{
test: /\.scss$/,
use: [
"style-loader", //3. Inject styles into DOM
"css-loader", //2. Turns css into commonjs
"sass-loader" //1. Turns sass into css
]
}
]
},
devServer: {
hot: true,
compress: true,
publicPath: '/static/dev/'
},
});
settings.py
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 2.2.4.
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!
SECRET_KEY = ')u)=q2gh%++e1!h(q5*+sa^nn8ygszg=dqfr7a!0ogzleh=i6k'
# 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',
# Third party apps
'webpack_loader',
'crispy_forms',
'django_extensions'
]
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 = 'app.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 = 'app.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'),
}
}
# 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/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'assets/staticfiles'),
os.path.join(BASE_DIR, 'static/'),
]
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/dev/',
'POLL_INTERVAL': 0.1,
'TIMEOUT': None,
'STATS_FILE': os.path.join(BASE_DIR, 'assets/bundles/dev/stats.json')
}
}
# Live reload server setting
WEBPACK_LIVE_SERVER = True
if DEBUG and WEBPACK_LIVE_SERVER:
WEBPACK_LIVE_SERVER_CONFIG = {
'ADDRESS': 'http://localhost:8080/static/dev'
}
if not DEBUG:
WEBPACK_LOADER.update({
'DEFAULT': {
# 'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'staticfiles/bundles/stats.json')
}
})
CRISPY_TEMPLATE_PACK = 'bootstrap4'
# For Media
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")

In table.html you use the tag render_bundle but you have not loaded those tags (Extending some template that loads those tags does not mean this template can also use them). Load the tags at the start of the template:
{% extends "base.html" %}
{% load render_bundle from webpack_loader %}
<!-- Rest of the template -->
{% render_bundle 'table' 'js' %}
<!-- Rest of the template -->

Related

Deploying a Django app to heroku. Debug False

I am trying to deploy my app to heroku.
I successfully deployed to app after dealing with some bugs(the CSS wouldn't load, or images wouldn't load). Now when I deploy the app works fine, when DEBUG = True.
When I change DEBUG = False all the images fail to load.
Here is my code:
settings.py
"""
Django settings for DBSF project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import django_heroku
import os
from dotenv import load_dotenv
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']
AUTH_USER_MODEL = 'social.User'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['desolate-lowlands-74512.herokuapp.com', 'localhost', '127.0.0.1']
# Application definition
INSTALLED_APPS = [
'channels',
'social',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'DBSF.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'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',
],
},
},
]
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
WSGI_APPLICATION = 'DBSF.wsgi.application'
ASGI_APPLICATION = 'DBSF.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'EST'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT= os.path.join(BASE_DIR, 'media/')
MEDIA_URL= "/media/"
Here's asgi.py
"""
ASGI config for DBSF project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import social.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DBSF.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
social.routing.websocket_urlpatterns
)
),
})
here's wsgi.py
"""
WSGI config for DBSF project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DBSF.settings')
application = get_wsgi_application()
heres the procfile.windows
web: python manage.py runserver 0.0.0.0:5000
heres the procfile
web: gunicorn DBSF.wsgi
heres layout.html
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<script crossorigin src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<script type='text/babel' src="{% static 'social/javascript/react_components.js' %}"></script>
<script type="text/babel" src="{% static 'social/javascript/layout.js' %}"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#rc/dist/js.cookie.min.js"></script>
{% block head %}{% endblock %}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="{% static 'social/styles/base.css' %}">
<link rel="shortcut icon" type="image/png" href="{% static 'social/favicon/favicon.ico' %}"/>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<nav class='main_nav'>
<a href="{% url 'index' %}" title='homepage'>DBSF</a>
<form action="/find_friends" method="GET">
<input name='search_term' type='text' placeholder='Search for friends'>
<input class='search_friends_button' type="submit" value='🔍'></form>
<a href="{% url 'profile' %}">
{% if user.profile_pic.url != '' %}
<img class="profile_pic_small_icon" src="{{user.profile_pic.url}}" alt="profile_pic">
{% else %}
<img class='profile_pic_small_icon' src="{% static 'social/core_images/no_image.jpg' %}" alt="{{user}} hasn't uploaded an image yet">
{% endif %}
{{user|title}}
</a>
Messages
<form class="logout_form" action="{% url 'logout' %}" method="post">
{% csrf_token %}
<a class='logout_a' href="/logout">Log out</a>
</form>
</nav>
<div class="messages">
<h1>{{message}}</h1>
</div>
<div class="side_bar">
<h4>Friend Requests</h4>
<div id="friendship_request_div"></div>
</div>
<div class="main">
{% block body %}{% endblock %}
</div>
<div class="friends_right_div">
<h4>Friends</h4>
<div id='friendship_div'></div>
</div>
<div id='message_box' class='message_box'>
</div>
</body>
</html>
So basically I need to figure out why DEBUG = False doesn't allow the images to load.
Let me know if it is clear what I am asking or if you need any other files to help me!
Thank you
In deployment mode, you need some bucket(e.g, Amazon S3) to store your static (and media) files and serve them from there. Heroku also has some plugins to do so(needs credit card). Heroku doesnot provide any way to do so without a bucket. That is why, they are not rendering. Also with DEBUG=True, all the media files will still vanish after 30 minutes as heroku runs on dynos and dynos refresh after every 30 minutes thus removing all the media files.
Try putting this in your urls.py:
from django.views.static import serve
and this in your urlpatterns:
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
In production you'd typically have nginx or something else serving media files like images. If you just want a quick and dirty way to still see them with DEBUG = True then this should add the media routes to the url patterns.

Django ajax search not returning result but the url prints in console

I am developing a Django Ajax search that searches through a list of college courses. After I finished implementing, I realized that the search doesn't work. However, my shell prints out the updated URL. Here is what I mean.
If I search for BUS, My console would do this, but my HTML file wouldn't change:
Note: If it's easier, I can add a GitHub link to my code
UPDATE: Github link
$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
August 13, 2020 - 11:37:25
Django version 3.0, using settings 'smore.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[13/Aug/2020 11:37:28] "GET /courses/ HTTP/1.1" 200 19376
Not Found: /artists/
[13/Aug/2020 11:37:35] "GET /artists/?q=BUS HTTP/1.1" 404 2092
I can't seem to understand where the /artists/ is coming from. I changed the endpoints and the URLs respectively. Here are my files
urls.py
from django.contrib import admin
from django.urls import path
from search import views as v
urlpatterns = [
path('admin/', admin.site.urls),
path('courses/', v.course_view, name = "courses")
]
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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = blahblahblah
# 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',
'search.apps.SearchConfig',
]
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 = 'smore.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'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 = 'smore.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/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/3.0/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/3.0/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/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
# Don't forget to use absolute paths, not relative paths.
os.path.join(BASE_DIR, "static/"),
os.path.join(BASE_DIR, "static/search/"), # for the css file
)
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
views.py
from django.shortcuts import render
from .models import collegeCourse
from django.template.loader import render_to_string
from django.http import JsonResponse
# Create your views here.
# core/views.py
def course_view(request):
ctx = {}
url_param = request.GET.get("q")
if url_param:
courses = collegeCourse.objects.filter(course_code__icontains=url_param)
else:
courses = collegeCourse.objects.all()
ctx["courses"] = courses
if request.is_ajax():
html = render_to_string(
template_name="partial-courses.html",
context={"courses": courses}
)
data_dict = {"html_from_view": html}
return JsonResponse(data=data_dict, safe=False)
return render(request, "courses.html", context=ctx)
Base.html
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Search | Courses</title>
<!-- Bootstrap-->
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"crossorigin="anonymous">
<!-- JQuery -->
<script src="{% static 'javascript/jquery-3.4.1.min.js' %}"></script>
<!-- FontAwesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">
<link href="{% static "main.css" %}" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
{% block content %}
{% endblock %}
</div>
{% block footer %}
<script type="text/javascript" src="{% static "javascript/main.js" %}"></script>
{% endblock %}
</body>
</html>
courses.html
{% extends "base.html" %}
{% block content %}
<h3>Courses</h3>
<div class="row">
{# icon and search-box #}
<div class="col-6 align-left">
<i id="search-icon" class="fas fa-search"></i>
<input id="user-input" placeholder="Search">
</div>
{# course section #}
<div id="replaceable-content" class="col-6">
{% include 'partial-courses.html' %}
</div>
</div>
{% endblock %}
partial-courses.html
{# partial-courses.html #}
{% if courses %}
<ul>
{% for course in courses %}
<li>{{ course.course_code }}</li>
{% endfor %}
</ul>
{% else %}
<p>No course found.</p>
{% endif %}
Main.js
const user_input = $("#user-input")
const search_icon = $('#search-icon')
const courses_div = $('#replaceable-content')
const endpoint = '/courses/'
const delay_by_in_ms = 700
let scheduled_function = false
let ajax_call = function (endpoint, request_parameters) {
$.getJSON(endpoint, request_parameters)
.done(response => {
// fade out the courses_div, then:
courses_div.fadeTo('slow', 0).promise().then(() => {
// replace the HTML contents
courses_div.html(response['html_from_view'])
// fade-in the div with new contents
courses_div.fadeTo('slow', 1)
// stop animating search icon
search_icon.removeClass('blink')
})
})
}
user_input.on('keyup', function () {
const request_parameters = {
q: $(this).val() // value of user_input: the HTML element with ID user-input
}
// start animating the search icon with the CSS class
search_icon.addClass('blink')
// if scheduled_function is NOT false, cancel the execution of the function
if (scheduled_function) {
clearTimeout(scheduled_function)
}
// setTimeout returns the ID of the function to be executed
scheduled_function = setTimeout(ajax_call, delay_by_in_ms, endpoint, request_parameters)
})
Kind of a blunder error. But I didn't properly import my model. Instead of from .models import whatever, I needed to do from appname.models import whatever

Unable to load CSS files into Django 1.10

I am new to Django. I am developing a dynamic website which include CSS in it.
I am using template inheritance.When I try to include CSS files I am getting a "404 Page not Found" error for CSS file. Please help me.
Here's my project structure:
Here's my urls.py file:
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
url(r'^courses/', include('courses.urls')),
url(r'^admin/', admin.site.urls),
url(r'^$', views.hello_world),
]
urlpatterns += staticfiles_urlpatterns()
Here's my settings.py file:
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/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '5%#*z=7o5iap!lnr7(%*(2rsl#*b-ufjy!ia$8z08d(6d8!j-#'
# 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',
'courses',
]
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 = 'learning_site.urls'
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 = 'learning_site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/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.10/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.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATIC_FILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Here's my layout.html file:
{% load static from staticfiles %}
<html>
<head>
<title>
{% block title %}{% endblock title %}
</title>
<link rel='stylesheet' href="{% static 'css/layout.css' %}">
</head>
<body>
{% block content %}print something for fun...{% endblock content %}
</body>
</html>
Here's my home.html file:
{% extends 'layout.html' %}
{% block title %}Hello World {% endblock title%}
{% block eontent %}
<h1>
welcome!!!
</h1>
{% endblock content %}
If you are using Django 1.10
here is the documentation of STATICFILES_DIRS
change your
STATIC_FILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
to
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'static',
]
And in your base html change the {% load static from staticfiles %} to {% load static %}
STATIC_FILES_DIRS is no django settings config name use STATICFILES_DIRS instead.
If your static folder is inside you base project app .
Something like.
django_project (your manage.py is here) -> django_project -> static
then your static file config should be like.
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'django_project/static'),
)
You shouldn't need any changes in your urls for this.
Update: The above doesn't seem to be true.
Your template syntax for block tag is incorrect.
Can you please fix that and check . You don't endblock and blockname
<html>
<head>
<title>
{% block title %}{% endblock %}
</title>
<link rel='stylesheet' href="{% static 'css/layout.css' %}">
</head>
<body>
{% block content %}print something for fun...{% endblock %}
</body>
</html>
Update 2:
Also template context process needs to be like this.
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.core.context_processors.static",
'django.contrib.messages.context_processors.messages',
],
},
},
]

Django 1.10 claims template does not exist, but it clearly does

But if I copy and paste that location into firefox, the template is there...
views.py:
def artists(request):
artists = Artist.objects.all()
template = loader.get_template('artists/index.html')
context = {'artists': artists,}
return HttpResponse(template.render(context, request))
index.html:
{% extends "site_base.html" %}
{% load i18n %}
{% block head_title %}pinax-project-account{% endblock %}
{% block body_class %}home{% endblock %}
{% block body_base %}
<section class="jumbotron">
<div class="container">
{% include "_messages.html" %}
<h1>{% blocktrans %}Welcome to<br>pinax-project-account{% endblocktrans %}</h1>
<p>
{% blocktrans %}
In addition to what is provided by the "zero" project, this project
provides thorough integration with django-user-accounts, adding
comprehensive account management functionality. It is a foundation
suitable for most sites that have user accounts.
{% endblocktrans %}
</p>
{% if not user.is_authenticated %}
{% url "account_login" as login_url %}
{% url "account_signup" as signup_url %}
<p>{% blocktrans %}You can Log In or Sign Up to try out the site.{% endblocktrans %}</p>
{% endif %}
</div>
</section>
<section>
<div class="container">
<h2 class="text-center">{% blocktrans %}What is Pinax?{% endblocktrans %}</h2>
<p class="lead">
{% blocktrans %}
<b>Pinax</b> is an open-source platform based on Django and
intended to provide a starting point for websites. It takes
care of the things that many sites have in common, so you can
focus on what makes your site different.
{% endblocktrans %}
</p>
<div class="feature-columns">
<div>
<i class="fa fa-cubes fa-3x"></i><br>
{% blocktrans %}
<b>Starter projects</b> provide project layout,
scaffolding, already integrated components and
ready-to-go code.
{% endblocktrans %}
</div>
<div>
<i class="fa fa-puzzle-piece fa-3x"></i><br>
{% blocktrans %}
<b>Reusable apps</b> provide common
infrastructure, back-end functionality,
and user-facing components.
{% endblocktrans %}
</div>
<div>
<i class="fa fa-tint fa-3x"></i><br>
{% blocktrans %}
<b>Themes</b> provide default templates and
stylesheets for quick prototyping and easy customization.
{% endblocktrans %}
</div>
</div>
</div>
</section>
<section>
<div class="container">
<p class="lead text-center">
{% blocktrans %}
See pinaxproject.com
for more information.
{% endblocktrans %}
</p>
</div>
</section>
{% endblock %}
Settings.py:
import os
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
BASE_DIR = PACKAGE_ROOT
DEBUG = True
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "dev.db",
}
}
ALLOWED_HOSTS = [
"localhost",
]
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = "UTC"
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "en-us"
SITE_ID = int(os.environ.get("SITE_ID", 1))
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PACKAGE_ROOT, "site_media", "media")
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = "/site_media/media/"
# Absolute path to the directory static files should be collected to.
# Don"t put anything in this directory yourself; store your static files
# in apps" "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(PACKAGE_ROOT, "site_media", "static")
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = "/site_media/static/"
# Additional locations of static files
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, "static", "dist"),
]
STATICFILES_STORAGE = "django.contrib.staticfiles.storage.ManifestStaticFilesStorage"
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
# Make this unique, and don't share it with anybody.
SECRET_KEY = "#t_)=9g2nssm4!6rw^vq(1_sqbnxi4zky--b8!crlvp(f1r=ol"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
os.path.join(PACKAGE_ROOT, "templates"),
os.path.join(BASE_DIR, 'templates/'),
'/home/shawn/Workspace/WebSites/artCollective/ac3/ac3/templates/ac3/',
],
"APP_DIRS": True,
"OPTIONS": {
"debug": DEBUG,
"context_processors": [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.debug",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.template.context_processors.request",
"django.contrib.messages.context_processors.messages",
"account.context_processors.account",
"pinax_theme_bootstrap.context_processors.theme",
],
},
},
]
MIDDLEWARE = [
"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 = "ac3.urls"
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = "ac3.wsgi.application"
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.messages",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.staticfiles",
# theme
"bootstrapform",
"pinax_theme_bootstrap",
# external
"avatar",
"account",
"pinax.eventlog",
"pinax.webanalytics",
# project
"ac3",
"artists",
]
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"filters": {
"require_debug_false": {
"()": "django.utils.log.RequireDebugFalse"
}
},
"handlers": {
"mail_admins": {
"level": "ERROR",
"filters": ["require_debug_false"],
"class": "django.utils.log.AdminEmailHandler"
}
},
"loggers": {
"django.request": {
"handlers": ["mail_admins"],
"level": "ERROR",
"propagate": True,
},
}
}
FIXTURE_DIRS = [
os.path.join(PROJECT_ROOT, "fixtures"),
]
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
ACCOUNT_OPEN_SIGNUP = True
ACCOUNT_EMAIL_UNIQUE = True
ACCOUNT_EMAIL_CONFIRMATION_REQUIRED = False
ACCOUNT_LOGIN_REDIRECT_URL = "home"
ACCOUNT_LOGOUT_REDIRECT_URL = "home"
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 2
ACCOUNT_USE_AUTH_AUTHENTICATE = True
AUTHENTICATION_BACKENDS = [
"account.auth_backends.UsernameAuthenticationBackend",
]
I have
spent hours on what should have a trivial solution. Django is looking in the correct location for the template, why can it not be rendered?
Try to remove slash after templates from settings.py in
os.path.join(BASE_DIR, 'templates')
I encountered the same issue, and finally resolved it. If you created the html file in notepad;
copy and paste what you have in the notepad file into a WordPad file.
save as...then select a plain text file in the drop down bar
Goodluck!

When trying to run a Django project I get the NoReverseMatch error

I am trying to run this project on local server and I get the follwoing error:
My url file is as follows:
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
url(r'^courses/', include('courses.urls', namespace='courses')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.hello_world, name='hello_world'),
]
urlpatterns += staticfiles_urlpatterns()
And this is the views file
from django.shortcuts import render
def hello_world(request):
return render(request, 'home.html')
This is the setting file
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&s5%_8r2y$9%pbnph*xy*%v^a_!vc0bmbqz%(+l#pc#k7n2r)+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'courses',
)
MIDDLEWARE_CLASSES = (
'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',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'learning_site.urls'
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 = 'learning_site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
And this is the home.html file
{% extends "layout.html" %}
{% block title %}Well hello there!{% endblock %}
{% block content %}
<h1>Welcome!</h1>
{% endblock %}
this is the template file:
{% load static from staticfiles %}
<!doctype html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static 'css/layout.css' %}">
</head>
<body>
<div class="site-container">
<nav>
Home
Courses
</nav>
{% block content %}{% endblock %}
</div>
</body>
</html>
And this is the layout.html file
{% load static from staticfiles %}
<!doctype html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static 'css/layout.css' %}">
</head>
<body>
<div class="site-container">
<nav>
<!-- Home -->
Home
Courses
</nav>
{% block content %}{% endblock %}
</div>
</body>
</html>
Not able to figure out what the problem is. please help. thanks.
You're trying to reverse the url for 'views.helloworld'. But, that's not the name of the url you've defined. That's the view name. Change your urls.py file to:
url(r'^$', views.hello_world, name='hello_world'),
and then use:
Home
I think the problem might be in the urls.py file
Could you try importing the views as
from courses import views
As per Rohits' suggestions above I made the changes and it worked.
Tip: Dont comment out the changes, delete them! Quoting Rohit "Django will try to resolve the {% url %} tags before rendering the HTML page. So, even though you comment that out, it still tries to reverse the url"