Error at TemplateDoesNotExist at / - django

I am using django 1.10.2 version and I got an error which says TemplateDoesNotExist at /
I don't know why it's happening, I tried fixing it with:
'DIRS':
['C:\Users\rahul\django-tuts\cms\blog\templates\blog\post'],
or
'DIRS': [os.path.join(os.path.dirname(file), '..//',
'templates').replace('\', '/')],
Still encountered the same error.
Following are my files content:
settings.py
Django settings for cms project.
Generated by 'django-admin startproject' using Django 1.10.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
# 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 = 'u2!61zgb-klaf=qh)bh#9brkxt%vy5!!esg5=uvs!ahh%#t$-4'
# 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',
'blog',
]
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 = 'cms.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
# 'DIRS': ['C:\\Users\\rahul\\django-tuts\\cms\\blog\\templates\\blog\\post'],
# 'DIRS': [os.path.join(os.path.dirname(__file__), '..//', 'templates').replace('\\', '/')],
'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 = 'cms.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 = 'UTC'
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/'
urls.py
"""cms URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', include('blog.urls', namespace='blog', app_name='blog')),
]
views.py
from django.shortcuts import render
from .models import Post
# Create your views here.
def list_of_post(request):
post = Post.objects.all()
template = 'blog/post/list_of_post.html'
context = {'post': post}
return render(request, template, context)

I think you should consider your project root:
Should be like this, considering your templates/blog folder:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates/blog'],
'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',
],
},
},
]
Then to use the template you have to specify only the relative path in the templates/blog folder:
from django.shortcuts import render
from .models import Post
# Create your views here.
def list_of_post(request):
post = Post.objects.all()
template = 'post/list_of_post.html'
context = {'post': post}
return render(request, template, context)
It should work.

Related

How can I solve the error "page not found(404)" in my 1st django project?

I'm very new to django and I stuck in my first project
the error says Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/about
using the URLconf defined in emuhay.urls, Django tried these URL patterns, in this order:
admin/
The current path, about, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
I'm expecting "Contat page" but page not found displayed every time
my code is below
#Url code
from django.contrib import admin
from django.urls import path
from django.http import HttpResponse
def home(request):
return HttpResponse('Home Page')
def contact(request):
return HttpResponse('Contact Page')
urlpatterns = [
path('admin/', admin.site.urls),
path('',home),
path('about/',contact),
]
#setting.py
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'yra+iwr3x_)#ssxj)e%h^7=m(te0mh!_4xx61g7j2j4y)o9z&$'
# 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',
'hihi',
]
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 = 'emuhay.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 = 'emuhay.wsgi.application'
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
This part of the official docs would be helpful
Try this in your urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home'),
path('about/', contact, name='contact'),
]

Django: TemplateDoesNotExist at /

I am using Django 3.0.7 and have a project named starling and an app named piggybank. I placed my index.html inside templates/starling inside the piggybank directory
The following urls.py is inside piggybank:
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
The urls.py in starling (project) is:
"""starling 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("", include("piggybank.urls")),
path('admin/', admin.site.urls),
]
My full settings.py:
"""
Django settings for starling project.
Generated by 'django-admin startproject' using Django 3.0.7.
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 = ')4^iro*2zhq%f9w2du33eu#ja%)&_cqltplq9b2lzu+qf#xz(6'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'starling.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 = 'starling.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/'
Template-loader post mortem:
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: /home/anna/starling/lib/python3.6/site-packages/django/contrib/admin/templates/starling/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /home/anna/starling/lib/python3.6/site-packages/django/contrib/auth/templates/starling/index.html (Source does not exist)
And lastly an image of my directories:
To fix the problem, add piggybank to INSTALLED_APPS in your settings.
In your TEMPLATES setting, you have:
'APP_DIRS': True,
This is the default, and means that Django will look at the templates directory for each app in INSTALLED_APPS. In the post mortem you can see:
django.template.loaders.app_directories.Loader: /home/anna/starling/lib/python3.6/site-packages/django/contrib/admin/templates/starling/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /home/anna/starling/lib/python3.6/site-packages/django/contrib/auth/templates/starling/index.html (Source does not exist)
It's not looking in the piggybank/templates directory because you haven't added piggybank to INSTALLED_APPS yet.
You need are missing TEMPLATES DIR
read this django templates
try this
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], # your dir template path
I got this error when I forgot to add the app in installed apps:
INSTALLED_APPS = [
...
'app.apps.AppConfig',
...
]
app is the name of you app, so if your apps name was myApp,
then it would be: 'myApp.apps.MyappConfig',

Getting the except django.core.exceptions.ImproperlyConfigured while querying DB

I am trying to fetch a few rows from the DB using the following code in my views.py:
from django.http import HttpResponse
from django.shortcuts import render
from fusioncharts.models import QRC_DB
def display_data(request,component):
query_results = QRC_DB.objects.get(component_name__contains=component)
return HttpResponse("You're looking at the component %s." % component)
For the above, I am getting the following exception:
django.core.exceptions.ImproperlyConfigured: The included URLconf 'Piechart_Excel.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
However whenever I am removing/commenting out the below line, the above exception disappears:
query_results = QRC_DB.objects.get(component_name__contains=component)
The 2 urls files are as follows:
urls.py under the app directory
from django.urls import path
from fusioncharts import views
urlpatterns = [
path('push-data/', views.push_data, name='push-data'),
path('home/', views.home, name='home'),
path('display_data/<str:component>', views.display_data, name='display_data'),
]
and urls.py under the main project directory
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('fusioncharts.urls'))
]
Edit:
Settings.py file is as follows:
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/
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'fusioncharts',
]
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 = 'Piechart_Excel.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'fusioncharts', 'templates', 'fusioncharts'),],
'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 = 'Piechart_Excel.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'QRC_Report_First_Project',
'USER':'xxxx',
'PASSWORD':'xxxx',
'HOST':'localhost',
'PORT':'3306'
}
}
# 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/'
Can anyone say what's going wrong? How come just one line of code which queries the DB is causing the above exception?

want to protect views function from anonymous user using decorators

i have django website that require authentication and user login in order to use some functions and view templates.
i used the decorator #login_required but nothing is change and anyone still able to view html page and use any function.
what am i missing in my code ??
views.py
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required(login_url="/login/")
def create(request):
...
return render(request,'blog/create.html')
urls.py
"""ABdatabase URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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
from blog.views import *
from .views import *
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('',home),
path("usr/logMeIn", logMeIn),
path("usr/logMeOut", logMeOut),
path('mainpage',mainpage,name="main"),
path('blog/', include('blog.urls')),
]
blog.urls.py
# from django.contrib import admin
from django.urls import path
from .views import *
# from django.conf.urls.static import static
# from django.conf import settings
urlpatterns = [
path('create/', create),
path('list/', listANDsearch,name="list"),
path('details/<int:pk>/',get_details,name= 'result'),# using <int:id> in order to display the id
path('listdd',homeInputlineBottom),
]
settings.py
"""
Django settings for ABdatabase project.
Generated by 'django-admin startproject' using Django 2.2.2.
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 = '5(%xarj8+c73-jmn*666gsmj1w5ix%vha8-c1vocevb=2#(()e'
# 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',
'blog',
]
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 = 'ABdatabase.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',
# 'blog.context_processors.home',
],
},
},
]
WSGI_APPLICATION = 'ABdatabase.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 = 'canada'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS= [
os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
even after i used the decorator nothing it change.
try this
def create(request):
user = request.user
if not user.is_authenticated:
return redirect('/') # Redirect whatever you want

Django 2.0, URL Routes Causing Max Recursion with check_method

I'm totally new to Django, and I'm having a problem adding a Django "app" to a created Django "project". I'm using Docker and Docker-Compose and when I try to build and spin up my instance with the "documents" app added it throws maximum recursion errors.
This problem is NOT present if I remove the documents app from the project, so there's obviously something misconfigured with my app.
Does anyone see what I'm doing wrong to set my default URL ('') to the Index view in documents?
Directory Structure
app/
|-django_nlp/
|-settings.py
|-urls.py
|-wsgi.py
|-documents/
|-templates/
|-index.html
|-apps.py
|-views.py
|-Dockerfile
|-docker-compose.yml
|-manage.py
django_nlp/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__)))
# /usr/src/app
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ixoz#2d4=m#k#%1#!hhr2ei82t4x$$e)n9oxrq66mzq556k59#'
# 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',
'documents'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'django_nlp.urls'
#Get the absolute path of the settings.py file's directory
BASE_PATH = os.path.dirname(os.path.realpath(__file__ ))
# /usr/src/app/django_nlp
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or
# "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
#Add Templates to the absolute directory
# os.path.join(BASE_PATH, "templates")
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR,
BASE_PATH
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'django_nlp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
django_nlp/urls.py
from django.conf.urls import url
from django.contrib import admin
# from documents import views
# import documents
from documents.views import Index
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', Index.as_view())
# url(r'$^', documents.views.index, name='index')
]
documents/views.py
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import TemplateView
# def index(request):
# return HttpResponse('Hello, welcome to the index page.')
class Index(TemplateView):
template_name = "text-form.html"
data = {'text': ''}
def get(self, request, *args, **kwargs):
form = self.form_class(data=self.data)
return render(request, self.template_name, data)
Thanks for your time!
If you working on Django 2.0, you should read this docs: https://docs.djangoproject.com/en/2.0/ref/urls/, the url configuration in this version has changes. But, if you realy want to use regex in Django 2.0, you can change:
from django.conf.urls import url
to;
from django.urls import re_path
example in your case;
from django.conf.urls import url
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', Index.as_view())
# url(r'$^', documents.views.index, name='index')
]
to;
from django.urls import re_path
urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^$', Index.as_view()),
]