I try to learn Django CRUD from this tutorial: https://www.javatpoint.com/django-crud-example My Django version is 2.1.7 and my IDE is VisualStudio. When I run the project all the pages have an error. the error cames bellow.
TemplateDoesNotExist at /index
show.html
Request Method: GET
Request URL: http://localhost:52322/index
Django Version: 2.1.7
Exception Type: TemplateDoesNotExist
Exception Value:
show.html
Exception Location: E:\Django_Try\DjangoWebProject5\DjangoWebProject5\env\lib\site-packages\django\template\loader.py in get_template, line 19
Python Executable: E:\Django_Try\DjangoWebProject5\DjangoWebProject5\env\Scripts\python.exe
Python Version: 3.6.6
Python Path:
['E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5',
'',
'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5',
'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5\\env\\Scripts\\python36.zip',
'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\DLLs',
'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\lib',
'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64',
'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5\\env',
'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5\\env\\lib\\site-packages']
Server time: Tue, 5 Mar 2019 22:43:24 +0000
I added my Urls bellow:
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
from employee import views
urlpatterns = [
path('index', views.show),
path('admin/', admin.site.urls),
path('emp', views.emp),
path('show',views.show),
path('edit/<int:id>', views.edit),
path('update/<int:id>', views.update),
path('delete/<int:id>', views.destroy),
]
View:
from django.shortcuts import render, redirect
from employee.forms import EmployeeForm
from employee.models import Employee
# Create your views here.
def emp(request):
if request.method == "POST":
form = EmployeeForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/show')
except:
pass
else:
form = EmployeeForm()
return render(request,'index.html',{'form':form})
def show(request):
employees = Employee.objects.all()
return render(request,"show.html",{'employees':employees})
def edit(request, id):
employee = Employee.objects.get(id=id)
return render(request,'edit.html', {'employee':employee})
def update(request, id):
employee = Employee.objects.get(id=id)
form = EmployeeForm(request.POST, instance = employee)
if form.is_valid():
form.save()
return redirect("/show")
return render(request, 'edit.html', {'employee': employee})
def destroy(request, id):
employee = Employee.objects.get(id=id)
employee.delete()
return redirect("/show")
setting:
"""
Django settings for DjangoWebProject5 project.
Generated by 'django-admin startproject' using Django 1.9.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import posixpath
# 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.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '65ccf984-10e5-4c13-ab4d-9c0cf30e8b04'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
# Add your apps here to enable them
'employee',
'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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'DjangoWebProject5.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 = 'DjangoWebProject5.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static']))
My structure screenshot:
https://drive.google.com/open?id=1xRB0xcnkplZ4ktiyEblkMVeyJ1SpATDc
I think the error says the template does not exist but the templates exist. Please inform me what is wrong in my application.
Here, your troubles come from your understanding of your project architecture.
As you can see in your screenshoot here
Your template files are in the */DjangoWebProject5/employee/templates/employee/
So you have too call them with the right path like 'employee/index.html'
def emp(request):
if request.method == "POST":
form = EmployeeForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/show')
except:
pass
else:
form = EmployeeForm()
return render(request,'employee/index.html',{'form':form}) ## Here 'employee/index.html'
You can fix that on all your views.
Check this
It appears that TEMPLATE_DIRS was used prior to 1.8 but in the current version it has changed to a DIRS option in the TEMPLATES setting.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'/home/html/templates/lawrence.com',
'/home/html/templates/default',
],
},
]
Related
I am trying to make an e-commerce website in django.
I want to lay the rough pipeline using this code but when i search, for example- http://127.0.0.1:8000/shop/about - This 404 Error come on my screen. Please tell me what to do.
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/shop/about
Using the URLconf defined in ekona.urls, Django tried these URL patterns, in this order:
admin/
shop [name='ShopHome']
shop about [name='about']
shop contact/ [name='ContactUs']
shop tracker/ [name='Tracker']
shop search/ [name='Search']
shop prodview/ [name='ProdView']
shop checkout/ [name='Checkout']
blog
The current path, shop/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.
My settings.py is -
"""
Django settings for ekona project.
Generated by 'django-admin startproject' using Django 4.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
# 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/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-o5!u%!k$n7a)q_wqj$av#t7%xplhhtt1mkefs)(q$*79$b6guq'
# 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',
'shop',
]
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 = 'ekona.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 = 'ekona.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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',
},
]
My urls.py for this 'shop' page is-
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name='ShopHome'),
path('about', views.about, name='AboutUs'),
path('contact/', views.contact, name='ContactUs'),
path('tracker/', views.tracker, name='Tracker'),
path('search/', views.search, name='Search'),
path('prodview/', views.productView, name='ProdView'),
path('checkout/', views.checkout, name='Checkout'),
]
My views.py for this 'shop' page is-
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request,'shop/index.html')
def about(request):
return HttpResponse("We are at about")
def contact(request):
return HttpResponse("We are at contact")
def tracker(request):
return HttpResponse("We are at tracker")
def search(request):
return HttpResponse("We are at search")
def productView(request):
return HttpResponse("We are at product view")
def checkout(request):
return HttpResponse("We are at checkout")
Please tell me why's the error coming
In ekona.urls add the following:
path('shop/', include("shop.urls")),
Also, make sure to import include like so:
from django.urls import path, include
http://127.0.0.1:8000/shop/about
You don't have this url in your urls.py try:
http://127.0.0.1:8000/about
without /shop/
edit:
probably you have 2 urls.py files. One in project folder, and one in app folder. In your project urls.py you should add line:
path('shop/', include("shop.urls")),
and in yout app urls.py add line:
app_name = "shop"
I got a failure on url path issue when try to do an exercise with Django
"
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: URL route 'post/Title:Title/' uses invalid converter 'Title'.
"
1.I've tried change the variable Title to other path name but still no working.
2.I check the setting.py with eplease help me.
urls.py
from django.contrib import admin
from django.urls import path
from mblog.views import homepage, showpost
urlpatterns = [
path('admin/', admin.site.urls),
path('', homepage),
path('post/<Title:Title>/', showpost),
]
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Post
from datetime import datetime
# Create your views here.
def homepage(request):
posts = Post.objects.all() # SQL SELECT * FROM mblog_post(creat from models)
now = datetime.now()
return render(request, 'index.html', locals())
def showpost(request, Title):
try:
post = Post.objects.get(Title = Title)
if post != None:
return render(request, 'post.html', locals())
except:
return redirect('/')
setting.py
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve(strict=True).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 = 'key is erase!!'
# 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',
'mblog.apps.MblogConfig',
]
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 = 'jerryblog.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 = 'jerryblog.wsgi.application'
# 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 = 'zh-hant'
TIME_ZONE = 'Asia/Taipei'
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_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
in your urls.py do this:
path('post/<str:Title>/', showpost)
You have to try this it will help you to solve your error.You cant pass same name of value in primary key you should put "slug" either "int"
path('post/<slug:Title>/', showpost),
And in view change the argument of post variable as slug=title.
def showpost(request, Title):
try:
post = Post.objects.get(slug= Title)
if post != None:
return render(request, 'post.html', locals())
except:
return redirect('/')
Im following a tutorial about Django and I got this error and I dont know why its happening since Im following a book tutorial, I didnt have any error until now and I checked every piece of code, maybe its because Im using a new versio of Django?
This is 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 = 'REDACTED'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
# My apps
'learning_logs',
# Default django 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 = 'learning_log.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 = 'learning_log.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/'
This is views
from django.shortcuts import render
# Create your views here.
def index(request):
"""The home page for Learning Log."""
return render(request, 'learning_logs/index.html')
This is urls
"""Defines URL patterns for learning_logs."""
from django.urls import path
from . import views
app_name = 'learning_logs'
urlpatterns = [
# Home page
path('', views.index, name='index')
I just followed every step in the book and the folders paths for the projects so why I have this problem?
The answer was the html files were not actually html instead they were .txt
I faced a similar issue but my error was that I forgot to make another learning_logs folder inside the templates folder.
Another error was that I did not create an html file but a text file for 'index.html'.
Download a sample html file from online (https://filesamples.com/formats/html) and rename it to just "index" and edit it to include the content shown in the book.
step 1:
for urls.py
from django.urls import path
from . import views
app_name = "learning_logs"
urlpatterns = [
path('', views.index, name = 'index'),
]
step 2:
for views.py
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'index.html')
step 3:
Make a templates folder inside learning_logs app then, make a index.html folder inside templates folder......that's all.
Note: try this step.. this problem will be solve.
I am making a bot detection system for Twitter. I am facing problem in getting user account info. I have successfully made twitter authentication but when requesting user account info, I am getting this error
"code":215,"message":"Bad Authentication data."
My views.py code
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import render,redirect
from werkzeug.utils import redirect
from .forms import UserLoginForms
from django.contrib.auth import authenticate, login, logout
import requests
def home(request):
screenname = 'BarackObama'
r = requests.get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' + screenname + '&count=2')
print(r.text)
return render(request,'home.html')
def main_login_page(request):
return HttpResponseRedirect('/accounts/twitter/login')
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse(home))
My settings.py file. Here I am adding it because in it, at the end I have added my twiiter app key and secret.
"""
Django settings for FYPDjango project.
Generated by 'django-admin startproject' using Django 2.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+w5xq2*#!0zxi)q2+psrk+p^jd$-ndh9(z(dohb6xx9)aa)0z7'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['mysite.com' , 'localhost', '127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social_django',
# The following apps are required:
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.twitter',
]
SITE_ID = 1
# for oauth
AUTHENTICATION_BACKEND = [
# 'social_core_backends.twitter.TwitterOAuth',
# 'social_core.backends.google.GoogleOAuth2'
'allauth.account.auth_backends.AuthenticationBackend '
'django.contrib.auth.backends.ModelBackend',
]
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',
'social_django.middleware.SocialAuthExceptionMiddleware'
]
ROOT_URLCONF = 'FYPDjango.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',
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect', #For redirecting via login page
],
},
},
]
WSGI_APPLICATION = 'FYPDjango.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/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.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/2.1/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.1/howto/static-files/
STATIC_URL = '/static/'
#edited me here
STATIC_DIRS = 'static'
STATICFILES_DIRS = [
STATIC_DIRS,
]
SOCIAL_AUTH_TWITTER_KEY = 'xqTh9nHX5x4vN6AxKtnSjYsgs '
SOCIAL_AUTH_TWITTER_SECRET = '4qu506zZFM0t5rcxSb7mWvjMxx3UzxCY7hdlD2Am7ScnwMDhm6'
#
# SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '670284466947-42q8a99b1i76achlua9r4oq9as4kubu6.apps.googleusercontent.com'
# SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'SYx2HCGS1dbCfOIAkrN_ru9E'
LOGIN_REDIRECT_URL = 'home'
My urls.py file
from django.conf.urls import url
from django.contrib import admin
from django.urls import path,include
from FYPapp.views import user_logout, home, main_login_page
urlpatterns = [
# I want to add my app in the project so do this
path('',home,name='home'),
path('login',main_login_page,name='main_login_page'),
path('logout',user_logout,name='user_logout'),
path('accounts/', include('allauth.urls')),
path('admin/', admin.site.urls),
]
I am new to Django. So please help me with that problem. Thanks
This is not a problem with Django but with your Twitter API access. Per the "Getting Started" doc, you need to first apply for an account and receive your consumer key and access token. Then you need to use those to authenticate before making your call to statuses/user_timeline
Consider using the python package tweepy to make accessing the API easier.
Problem: template not loading with view ....
I've been following a django tutorial, hoping to get some templates working that I created. It looks like this.
app/templates
└── app
└── profile.html
Settings file looks like this:
"""
Django settings for demonstration project.
Generated by 'django-admin startproject' using Django 1.10.3.
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, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
# 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 = 'SOME_KEY_NON_PROD_TESTING_LOCALLY'
# 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',
'app',
]
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 = 'demonstration.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 = 'demonstration.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/'
The tutorial mentioned defining a template dir so I defined:
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
However, that didn't work so I also saw the DIRs option in the template stanza to I set that to the same value as TEMPLATE_DIRS that I added above.
I still don't see any change here. I am obviously missing something about the config that should point to the template but I'm stumped as to what that is at the moment.
The view:
from django.shortcuts import render, HttpResponse
import requests
import json
# Create your views here.
def index(request):
return HttpResponse('Hello World!')
def second_view(request):
return HttpResponse('This is the second view!')
def profile(request):
jsonList = []
req = requests.get('https://api.github.com/users/<username_here>')
jsonList.append(json.loads(req.content.decode()))
parsedData = []
userData = {}
for data in jsonList:
userData['name'] = data['name']
userData['email'] = data['email']
userData['public_gists'] = data['public_gists']
userData['public_repos'] = data['public_repos']
userData['avatar_url'] = data['avatar_url']
userData['followers'] = data['followers']
userData['following'] = data['following']
parsedData.append(userData)
return HttpResponse(parsedData)
The page source of localhost:8000/app/profile
{'followers': 1, 'public_repos': 5, 'avatar_url': 'https://avatars.githubusercontent.com/u/XXXXX', 'email': None, 'following': 4, 'name': None, 'public_gists': 1}
If your templates folder is in your project root folder and you have profile.html like this:
templates/app/profile.html then your view should be something like:
def some_view(request)
# some code
return render(request, 'app/profile.html')
Your profile view could be:
def profile(request)
# your code
return render(request, 'app/profile.html', {'data': userData})
Now, in your template profile.html, you can access the object data
Need to return render to view e.g. return render(request, 'app/profile.html', {'data': parsedData})