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!
Related
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 -->
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
Anytime I include a link to bootstrap.min.css lying locally in my Django project, my drop-down menu becomes non-clickable. Am a learning Django with no much knowledge of bootstrap. The tutorial am following used cdn to include the bootstrap but I downloaded it manually because of internet connection. Although the downloaded bootstrap is working but the drop-down menu is not working. Can someone help me out.. I can't continue learning at this stage. Thanks in advance.
The code is below.
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-">
<meta name="viewport" content="width=device-width, initial-scale=, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"
integrity="sha-MCw/SFnGEfJTGXwEOngsVZtNXFoaoApmYmi\ uXoPkFOJwJERdknLPMO"
crossorigin="anonymous">
<title>{% block title %}Newspaper App{% endblock title %}</title>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-">
<a class="navbar-brand" href="{% url 'home' %}">Newspaper</a>
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarCollapse" aria-controls="navbarCollapse"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
{% if user.is_authenticated %}
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link dropdown-toggle" data-toggle="dropdown "href="#" id="userMenu"
aria-expanded="false">
{{ user.username }}
</a>
<div class="dropdown-menu dropdown-menu-right"
aria-labelledby="userMenu">
<a class="dropdown-item"
href="{% url 'password_change'%}">Change password</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="{% url 'logout' %}">
Log Out</a>
</div>
</li>
</ul>
{% else %}
<form class="form-inline ml-auto">
<a href="{% url 'login' %}" class="btn btn-outline-secondary">
Log In</a>
<a href="{% url 'signup' %}" class="btn btn-primary ml-">
Sign up</a>
</form>
{% endif %}
</div>
</nav>
<div class="container">
{% block content %}
{% endblock content %}
</div>
<!-- Optional JavaScript -->
<!-- <jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-...slim.min.js" integrity="sha-qi/X+DzOrTabKJStQIAqVgRVzpbzosmXKp\ YfRvH+abtTEPijizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/\ ../ umd/popper.min.js" integrity="sha-ZMPrVomIykV++JUJjBkWLaUAdnaCwoqbB\ JiSnjAK/ lWvCWPIPm" crossorigin="anonymous"></script>
<script src="{% static 'js/bootstrap.min.js' %}"
integrity="sha-ChfqqxuZUCnJSK+MXmPNIyEZbWhIMqErYiqJxyMiZ\ OW/JmZQstwEULTy"
crossorigin="anonymous"></script>
</body>
</html>
#settings.py
"""
Django settings for helloworld_project project.
Generated by 'django-admin startproject' using Django 3.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z0qdn^sf&ill&gg%3myb#q)bzp$!^xnn-3(1po+blyjt1(bxyv'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
#local
'users.apps.UsersConfig',
'pages.apps.PagesConfig',
'articles.apps.ArticlesConfig',
#'blog.apps.BlogConfig',
#'accounts.apps.AccountsConfig',
#'posts.apps.PostsConfig',
#'page.apps.PageConfig',
# 3rd Party
'crispy_forms',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
TIME_ZONE = 'Africa/Lagos'
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 = 'helloworld_project.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 = 'helloworld_project.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/'
AUTH_USER_MODEL = 'users.CustomUser'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
'''EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = 'my_sendgrid_password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
#ACCOUNT_EMAIL_VERIFICATION = 'none'
'''
#views.py
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
# Create your views here.
class SignUpView(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html
The login ,logout, etc are in templates/registration/
#project_urls.py
"""helloworld_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('users.urls')),
path('users/', include('django.contrib.auth.urls')),
path('', include('pages.urls')),
#path('accounts/', include('django.contrib.auth.urls')),
#path('accounts/', include('accounts.urls')),
#path('', include('blog.urls')),
#path('', include('posts.urls')),
#path('', include('page.urls')),
#path('', include('pages.urls')),
]
And finally below is app_level url
#app_urls.py
from django.urls import path
from .views import SignUpView
urlpatterns = [
path('signup', SignUpView.as_view(), name='signup'),
]
Download the Jquery and Popper JS and put it in static folder
I once had an issue like this:
I hope my solution works for you.
The jquery library (jquery-.slim.min.js) you are using in your html file may not contain the functions necessary to create the dropdown effect use the jquery.min.js instead.
Remove this from your html file:
<script src="https://code.jquery.com/jquery-...slim.min.js" integrity="sha-qi/X+DzOrTabKJStQIAqVgRVzpbzosmXKp\ YfRvH+abtTEPijizo" crossorigin="anonymous"></script>
And Use the jquery.min below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Connect to the internet and refresh.
P:S
You can as well download the jquery.min.js by going to this jquery, it's just about 87kb. Then copy the code and save it as jquery.min.js in your static folder and connect it in your template like this:
<script src="{% static 'jquery.min.js' %}"></script>
And you won't need internet again to use it. I think the jquery library you used is the issue.
This happened to me before.
How I solved it was simply placing Jquery, then Popper js, followed by Boostrap js --- in that order.
I discovered the dropdown feature was dependent on Popper and Jquery.
Looking at your code, I see you followed that order, but I am not sure of the way you loaded boostrap using django.
Kindly get boostrap cdn, (same place you got Popper and Jquery), restart your server, clear browser cache with SHIFT + F5 and try again.
Make sure you have internet connection.
It was an error on line 23. Semicolon was wrongly placed by me.
When trying to login using the fb js_sdk I receive the below error. However using oauth2 works fine when I switch back to using it. Am I missing some configuration somewhere?
Internal Server Error: /accounts/facebook/login/token/
NoReverseMatch at /accounts/facebook/login/token/
Reverse for '' with arguments '()' and keyword arguments '{'request': <WSGIRequest: POST '/accounts/facebook/login/token/'>}' not found. 0 pattern(s) tried:
settings.py
INSTALLED_APPS = [
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'debug_toolbar',
]
MIDDLEWARE = [
'debug_toolbar.middleware.DebugToolbarMiddleware',
'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',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ BASE_DIR + '/main/templates/allauth/',],
'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',
'main.context_processors.get_search_query'
],
},
},
]
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
)
# ALLAUTH
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_SIGNUP_FORM_CLASS = 'main.forms.SignupForm'
ACCOUNT_PRESERVE_USERNAME_CASING = True
ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = True
ACCOUNT_SESSION_REMEMBER = True
SOCIALACCOUNT_PROVIDERS = {
'facebook': {
'METHOD': 'js_sdk',
'SCOPE': ['email', 'public_profile'],
'AUTH_PARAMS': {'auth_type': 'reauthenticate'},
'FIELDS': [
'id',
'email',
'name',
'first_name',
'last_name',
'verified',
'locale',
'timezone',
'link',
'gender',
'updated_time',
],
'EXCHANGE_TOKEN': True,
'VERIFIED_EMAIL': False,
'VERSION': 'v2.4',
}
}
login.html
{% extends "bases/bootstrap-auth.html" %}
{% load static %}
{% load i18n %}
{% load bootstrap3 %}
{% load account socialaccount %}
{% block head %}<meta name="robots" content="noindex">{% endblock %}
{% block extra_title %}{% trans "Log In" %}{% endblock %}
{% block inner-content %}
{% providers_media_js %}
{% get_providers as socialaccount_providers %}
<div class="text-center">
<h1 class="text-center">Log In</h1>
<small>Don't have an account? Signup, it's free!</small>
</div><hr>
<div class="row">
<div class="col-md-6 col-lg-6 col-md-offset-3">
<a title="{{provider.name}}" href="{% provider_login_url "facebook" method="js_sdk" %}"
class="btn btn-block btn-social btn-facebook">
<span class="fa fa-facebook"></span> Login with Facebook
</a>
<div class="strike">
<span>or</span>
</div>
</div>
</div>
{% endblock %}
{% block head_css %}
<link rel="stylesheet" href="{% static 'css/bootstrap-social.css' %}" rel="stylesheet">
{% endblock %}
urls.py
urlpatterns = [
url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/profile/$', main.views.account_profile, name='account_profile'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Please make sure you have correct login redirect URL setup in settings.py file
LOGIN_REDIRECT_URL = "/"
Did you add the correct code to your urls.py?
urlpatterns = [
...
url(r'^accounts/', include('allauth.urls')),
...
]
I have some photos uploaded but I was unable to see photos in temeplates
My template
{% extends 'base.html' %}
{% load staticfiles %}
{% block content %}
<div class="row ">
<div class="col-md-8">
<h1>{{ object.title }}</h1>
{% if object.productimage_set.count > 0 %}
<div>
{% for img in object.productimage_set.all %}
{{ img.image.file }}
{{ img.image.url }}
<img class='img-responsive' src='{{ img.image.url }}' />
</div>
{% endfor %}
</div>
{% endif %}
<div class="lead">{{ object.description }}</div>
</div>
</div>
My model
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=20)
active = models.BooleanField(default=True)
def __unicode__(self): # def __str__(self):
return self.title
class ProductImage(models.Model):
product = models.ForeignKey(Product)
image = models.ImageField(upload_to='product/')
Setting for media
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static", "my_static"),
]
STATIC_ROOT = os.path.join(BASE_DIR, "static", "static_root")
STATIC_URL = '/media/media_root/'
MEDIA_ROOT = os.path.join(BASE_DIR, "static", "media_root")
My urls
urlpatterns = [
url(r'^contact/', views.contact, name='contact'),
url(r'^$', views.ProductViewList.as_view(), name='ProductViewList'),
url(r'^(?P<pk>\d+)/$', views.ProductDetailView.as_view(), name='Product_Detail'),]
My folder structure
In the template {{ img.image.url }} gives -> product/mp3.jpg. But still I'm unable to see the image
The console shows that image is loaded from http://127.0.0.1:8080/product/1/product/mp3.jpg I guess there is some prob with the url to collect the image but not sure
Any help is much appreciated....Thanks in advance
You should add the MEDIA_URL to your settings.py, if you haven't.
In your case, the MEDIA_URL should be media_root. My Image links all have /media/....jpg.
In addition, you can specify the URLs:
from django.conf import settings
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
Here's some documentation from Django on this: https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-files-uploaded-by-a-user-during-development
I prefer keeping my media files separate from my static files, so during development I actually store mine in the project root. The following snippets use the project root as the media location, but you can easily adjust this by changing it to static/media_root if you'd prefer to keep your current location.
First make sure you've defined your media root in your settings.py file:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Then try adding the following to your project's urls.py file:
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}))