I called a template in the django render function, but django cannot find it
here is the django view code:
from django.shortcuts import render
# Create your views here.
def home_page(request):
return render(request, "index.html")
And after this I tried to check my settings.py and urls.py, but found nothing, and the file is also in the tamplate subfolder of the app
here is the directory structure:
│ .gitignore
│ db.sqlite3
│ funcational_test.py
│ manage.py
│
├─Terminal_equipment_management
│ │ asgi.py
│ │ settings.py
│ │ urls.py
│ │ view.py
│ │ wsgi.py
│ │ __init__.py
│ │
│ └─__pycache__
│
└─webui
│ admin.py
│ apps.py
│ models.py
│ tests.py
│ views.py
│ __init__.py
│
├─migrations
│
├─templates
index.html
the settings.py is:
INSTALLED_APPS = [
"api",
"webui",
'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': [],
'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 is:
from django.contrib import admin
from django.urls import path, include
from webui import views
urlpatterns = [
path("", views.home_page, name="home_page"),
]
But when I visit localhost:8000/, Django will report TemplateDoesNotExist at /
here is some Error Message:
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\ProgramData\Miniconda3\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\ProgramData\Miniconda3\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist)
When I copied the files to the above two folders, the template took effect.
I can't be sure what happened
By Google Translate
Add Template DIRS:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
],
},
},
]
I think you forgot to put s for template folder names
└─webui
│
├─tamplates
index.html
First, tamplates should be templates. Second, django looks inside a folder under templates for the app name. It seems redundant, and I agree, but that caused me issues when I was first using django.
└─webui
│
└─templates
│
└─webui
│
└─index.html
Related
I have the project like this:
├── manage.py
├── myProjet
│ ├── __init__.py
│ ├── settings.py
│ ├── templates
│ ├── urls.py
│ ├── wsgi.py
│ └── wsgi.pyc
├── app1
├── templates
When I run the project, I am always getting this error: TemplateDoesNotExist at/
I have tried everything, but I can't fix it. My settings.py file is this:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1',
]
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',
],
},
},
]
I have tried many ways, but I am always getting errors.
The error is raised on the signup function. The function is this:
def SignupPage(request):
if request.method=='POST':
uname=request.POST.get('username')
email=request.POST.get('email')
pass1=request.POST.get('password1')
pass2=request.POST.get('password2')
if pass1!=pass2:
return HttpResponse("Your password and confrom password are not Same!!")
else:
my_user=User.objects.create_user(uname,email,pass1)
my_user.save()
return redirect('login')
return render (request,'signup.html')
UPDATE ERROR
TemplateDoesNotExist at /
signup.html
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 4.1.6
Exception Type: TemplateDoesNotExist
Exception Value:
signup.html
Exception Location: /home/myPC/myProject/my_env/lib/python3.8/site-packages/django/template/loader.py, line 19, in get_template
Raised during: app1.views.SignupPage
Python Executable: /home//myProject/my_env/bin/python
Python Version: 3.8.10
Python Path:
['/home/myPC/myProject/pmTools_V1',
'/usr/lib/python38.zip',
'/usr/lib/python3.8',
'/usr/lib/python3.8/lib-dynload',
'/home/myPC/myProject/my_env/lib/python3.8/site-packages']
Since django is using pathlib I'd go with:
"DIRS": [
BASE_DIR / "templates"
],
in your settings.py templates section.
Try to replace:
'DIRS': ['templates'],
By:
'DIRS': [os.path.join(BASE_DIR, 'templates')]
in TEMPLATES section.
Update
Try:
from django.http import HttpResponse
from django.template import loader
def SignupPage(request):
template = loader.get_template('signup.html')
# Your code here
return HttpResponse(template.render(context, request))
First of all: I know, there are a few solutions for this online, but they wont work for me (because they use e.g. Jason or are just outdated)
I work on a project in Django and want to use ajax for one task:
I want to pass data, after it was processed by ajax, from my template file to my views file (with a POST request), to again make it visible in my templates file.
Templates-file --> Proccessed data --> POST-request --> views.py --> Template-file
But it just wont work for me.
My HTML-Templates-File:
...
<script type="text/javascript">
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
url: "/save",
data: {
'value': inputDataArray //I have already defined "inputDataArray" before
},
success: function (res, status) {
alert(res);
alert(status);
},
error: function (res) {
alert(res.status);
}
});
</script>
My views.py file:
def save(request):
if request.method == 'POST':
request_getdata = request.POST.get("value", None)
return render(request, "response.html", {"data":request_getdata})
urls.py file:
urlpatterns = [
path('', views.index , name='index'),
path('save', views.save , name='save'),]
So I try display it at "response.html"...
{{data}}
...but it just will reload the current page and does not pass any data to the response.html-file.
Does anyone knows what my error is here?
Thanks a lot in advance
P.S.: This is my project structure:
│ db.sqlite3
│ manage.py
│
├───myapp
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ __init__.py
│ │
│ ├───migrations
│ │ __init__.py
│ │
│ └───__pycache__
│ urls.cpython-39.pyc
│ views.cpython-39.pyc
│ __init__.cpython-39.pyc
│
├───static
│ └───myapp
│ └───css
│ index.css
│
├───templates
│ index.html
│ result.html
│
└───myapp
│ asgi.py
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
│
└───__pycache__
...
Instead of
urlpatterns = [
path('', views.index , name='index'),
path('save', views.save , name='save'),]
Try :
urlpatterns = [
path('', myapp.views.index , name='index'),
path('save',myapp.views.save , name='save')
I am having a structure of Django Project as:
│ db.sqlite3
│ manage.py
│
├───static
│ │ 1.jpg
│ │ bg1.jpg
│ │
│ └───css
│ login.css
│
├───templates
│ home.html
│ login.html
│ register.html
│
├───User
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ __init__.py
│ │
│ ├───migrations
│ │ │ __init__.py
│ │ │
│ │ └───__pycache__
│ │ __init__.cpython-38.pyc
│ │
│ └───__pycache__
│ admin.cpython-38.pyc
│ apps.cpython-38.pyc
│ models.cpython-38.pyc
│ urls.cpython-38.pyc
│ views.cpython-38.pyc
│ __init__.cpython-38.pyc
│
└───Website
│ asgi.py
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
│
└───__pycache__
settings.cpython-38.pyc
urls.cpython-38.pyc
wsgi.cpython-38.pyc
__init__.cpython-38.pyc
Settings.py
"""
from pathlib import Path
import os
# 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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-c*3$w_63#$^8g&_fn%r=-23n^e#nrmxzxt7eh*owsz^mlrk5dr'
# 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',
'User'
]
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 = 'Website.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 = 'Website.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.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/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIR= [os.path.join(BASE_DIR,'static'),
]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
And my Register.html File
{% load static %}
<html>
<head>
<title></title>
<style>
body
{
background:url({% static 'bg1.jpg' %});
}
</style>
</head>
<body>
<img src="{% static '1.jpg' %}">
<h1> HELOO </h1>
</body>
</html>
I have loaded the static and also the path for the static files still its not able to find image which i am providing in my html page. No issues while using template folder but only for static folder my project is not able to get the images and paste it on the browser.
Changing STATICFILES_DIR to STATICFILES_DIRS in setting.py helped to fix this error.
Thanks to Afzal Saiyed
I have seen this tutorial https://samulinatri.com/blog/django-ckeditor-codesnippet-hightlightjs-youtube/ and I have downloaded the youtube plugin here https://ckeditor.com/cke4/addon/youtube
Then I created the youtube folder and pushed it into it. Specifically my_project / static / ckeditor / ckeditor / plugins / youtube /
After I python manage.py runserver, field ['content'] show normal, field ['content1'] it doesn't work (does not display frames textarea).
Someone helped me check, I did something wrong. Thanks !!!
File model.py
class Posts(models.Model):
title = models.CharField(max_length=50)
content = RichTextUploadingField(extra_plugins=['codesnippet'],)
content1 = RichTextUploadingField(
config_name='special',
extra_plugins=['youtube'],
external_plugin_resources=[(
'youtube',
'/static/ckeditor/ckeditor/plugins/youtube/youtube/',
'plugin.js',
)],
)
File setting.py
INSTALLED_APPS = [
'suit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'ckeditor',
'ckeditor_uploader',
]
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full',
},
'special': {
'toolbar': 'Special',
'toolbar_Special': [
['Bold'], ['CodeSnippet', 'Youtube'],
],
'extraPlugins': ','.join(['codesnippet', 'youtube']),
}
}
File urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include(('accounts.urls', 'accounts'), namespace='accounts')),
path('blog/', include(('blog.urls', 'blog'), namespace='blog')),
path('ckeditor/', include('ckeditor_uploader.urls')),
]
if settings.DEBUG:
import debug_toolbar
debug_patterns = [
re_path(r'^__debug__/', include(debug_toolbar.urls)),
]
urlpatterns = debug_patterns + urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My_project
├── blog <= This my_app
│ ├── view.py
│ ├── form.py
│ ├── model.py
├── project <= Project settings directory
│ ├── __init__.py
│ ├── settings.py <= settings
│ ├── urls.py
│ └── wsgi.py
├── static
│ ├── ckeditor
│ ├── ckeditor_uploader
│ ├── ckeditor
│ ├── plugins
│ └── youtube
│ └── youtube
│ └── images
│ └── lang
│ └── plugin.js
│ └── ....
│ └── ...
│ └── ...
In your models.py file, you need to point to the directory where the plugin.js is.
I believe the directory you should refer to is this:
class Posts(models.Model):
title = models.CharField(max_length=50)
content = RichTextUploadingField(extra_plugins=['codesnippet'],)
content1 = RichTextUploadingField(
config_name='special',
extra_plugins=['youtube'],
external_plugin_resources=[(
'youtube',
'/static/ckeditor/ckeditor/plugins/youtube/',
'plugin.js',
)],
)
I am trying to incorporate a django application into a web site where static html accounts for the majority.
The directory structure is as follows.
root/
├ var/
│ └ www/
│ ├ html/
│ ├ static
│ │ ├style.css
│ │ ├base.js
│ │
│ ├ web/
│ ├head.html
│ ├footer.html
│ ├base.html
│
└ opt/
└ django/
├ project/
│
├ apps/
├ ├ views.py
├ template/
├ index.html
I want to make /opt/django/template/index.html read html in /var/www/html/web/.
I do not know how to include.
{% include "/var/www/html/web/head.html" %}was useless.
I do not want to change the directory structure.
Considering this as your directory structure:
root/
├ var/
│ └ www/
│ ├ html/
│ ├ static
│ │ ├style.css
│ │ ├base.js
│ │
│ ├ web/
│ ├head.html
│ ├footer.html
│ ├base.html
│
└ opt/
└ django/
├ project/
│
├ apps/
├ ├ views.py
├ template/
├ index.html
To use /var/www/html/web/head.html in your index.html.
Go to your settings.py and add this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'apps/template'),'/var/www/html/web/']
,
'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',
],
},
},
]
Now go to your index.html.
{% include "head.html" %}
I hope this will help.
Add /var/www/html/web/ to the DIRS option in the template configuration dictionary in your project settings.
https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-TEMPLATES-DIRS
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['/var/www/html/web/'], # won't work on Windows
'APP_DIRS': True,
'OPTIONS': {
# ... some options here ...
},
},
]
Then:
{% include "head.html" %}
Your templates can go anywhere you want. Your template directories are by using the DIRS option in the TEMPLATES setting in your settings file.
For each app in INSTALLED_APPS, the loader looks for a templates subdirectory. If the directory exists, Django looks for templates in there.
note
Paths should use Unix-style forward slashes, even on Windows.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'/var/www/html/web/',
],
},
]