Error 404 not found raises 500 when Debug set to False - django

I recently tried to implement a custom view for my 404 and 500 errors on my website. It works well when debug is set to True, i.e. both the custom views work well when called. But as soon as set my Debug to False only the error 500 will be raised
I tried already to call them by creating a url, both of the handler404 and handler500 custom view works well.
This is the view where it should raise an error 404 when badly called:
def arret(request, id):
""" Page that show an textuel """
view = 'search/arret.html'
arret = get_object_or_404(Arret, id=id)
arret.compute_bgeref_id()
query = request.GET.get('q', '')
form_class = DecisionForm()
title = arret.highlight_words(query,input_text=arret.title)
text = arret.highlight_words(query)
arret_judges = arret.arret_judges.all()
decision = arret.decision
return render(request, view, {'title': title,'text': text, 'date':arret.date, 'tag_string': arret.tag_string, 'tags': arret.get_n_tags(), 'articles': arret.get_n_law_articles(n=15),
'bgeref_id': arret.bgeref_ids.all(),"form": form_class, 'id':id, 'query' : query, 'decision': decision,'arret_judges':arret_judges, 'ATF':arret.source=='ATF'
})
Here you can find my 404 custom view:
def handler404(request, template_name="colorlib-error-404-19/index.html"):
response = render_to_response("colorlib-error-404-19/index.html")
response.status_code = 404
return response
it raises an error 500 when trying to find a non existing Arret.
this is what is written in the terminal
System check identified no issues (0 silenced).
June 22, 2019 - 08:55:31
Django version 2.0, using settings 'nora.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[22/Jun/2019 08:55:32] "GET /arret/100/?q=loi HTTP/1.1" 500 1435
Edit: add settings file
Here is my settings_file:
import os
from django.utils.translation import gettext_lazy as _
from requests_aws4auth import AWS4Auth
import elasticsearch
user = os.getenv('USER')
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ##########################
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
if user == 'user':
DEBUG = False
else:
DEBUG = True
# ALLOWED_HOSTS
if user == 'user': # Checks if the settings is on the website
ALLOWED_HOSTS = [ '.neuralen.ch', '.mstamenk.webfactional.com' ]
else :
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'haystack',
'search',
'authUser',
'debug_toolbar',
'haystack_panel',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'nora.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',
"django.template.context_processors.i18n",
],
},
},
]
#TEMPLATE_DIRS = ( failed attempt
# os.path.join(BASE_DIR, 'templates'),
#)
WSGI_APPLICATION = 'nora.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
if user == 'user': # Check if settings.py is on website server
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'nora_db',
'USER': 'neuralen',
'PASSWORD': #################,
'HOST': '127.0.0.1',
'PORT': '5432',
},
'nora_db_2': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'nora_db_2',
'USER': 'neuralen',
'PASSWORD': '################',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
else: # Otherwise, it's in local
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'nora_db_2': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'second_db.sqlite3'),
},
}
#DATABASE_ROUTERS = ['search.routers.SearchRouter']
# AWS
AACCESS_KEY = ##########################
SECRET_KEY = ##########################
REGION = 'us-east-1'
AWSHOST = 'https://search-nora-y6ko4vsxcd4255tcs4gznzbaou.us-east-1.es.amazonaws.com'
awsauth = AWS4Auth(AACCESS_KEY,SECRET_KEY,REGION,'es')
# Haystack connection to elasticsearch.
#https://stackoverflow.com/questions/35090762/django-haystack-using-amazon-elasticsearch-hosting-with-iam-credentials?rq=1
HAYSTACK_CUSTOM_HIGHLIGHTER ="nora.utils.nora_Highlighter"
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack_es.backends.Elasticsearch5SearchEngine',
#'URL': 'http://127.0.0.1:9200/',
'URL': AWSHOST,
'INDEX_NAME': 'nora',
'INCLUDE_SPELLING' : True,
'KWARGS': {
'port': 443,
'http_auth': awsauth,
'use_ssl': True,
'verify_certs': True,
'connection_class': elasticsearch.RequestsHttpConnection,
}
},
}
if user == 'user':
HAYSTACK_CONNECTIONS['default']['INDEX_NAME'] = 'nora-server'
else:
HAYSTACK_CONNECTIONS['default']['INDEX_NAME'] = 'nora'
# 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'
#LANGUAGE_CODE = 'fr'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
gettext = lambda x: x
LANGUAGES = (
('en', _('English')),
('fr', _('French')),
('de', _('German')),
)
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
if user == 'user': # Check if on website
STATIC_URL = 'https://neuralen.ch/django_nora_static/'
else: # Otherwise running in local
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static/"),
)
if user == 'user':
STATIC_ROOT = '/home/user/webapps/django_nora_static/'
else:
STATIC_ROOT = os.path.join(BASE_DIR, "static_root/")
# Authentification
LOGIN_URL = 'accounts/login'
LOGIN_REDIRECT_URL = '/'
#SMTP Email Serivce
#https://simpleisbetterthancomplex.com/tutorial/2016/06/13/how-to-send-email.html
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'testsite_app'
EMAIL_HOST_PASSWORD = '################'
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'TestSite Team <noreply#example.com>'
#EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # During development only
INTERNAL_IPS = [ '127.0.0.1']
DEBUG_TOOLBAR_PANELS = [
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.redirects.RedirectsPanel',
'haystack_panel.panel.HaystackDebugPanel',
]

It could be your settings file does not have ALLOWED_HOSTS
Django 1.5 introduced the allowed hosts setting that is required for security reasons.
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
Add your host here like ['www.example.com'] or ['*'] for a quick test, but don't use ['*'] for production.
Alternatively, it could be you're trying to access some static file without running collectstatic. In most cases, this should be a 404 after loading the response in the view, but if you're accessing them in the code, it could be a 500.

Related

Django email backed error brings socket error on smtp but send to console successful

I tried to send email via django Email message for account mail verification. When I send email via to console it send the activation link successfully but when it comes to sending via smtp I get TypeError: getaddrinfo() argument 1 must be string or none
Token generator
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
six.text_type(user.pk) + six.text_type(timestamp) +
six.text_type(user.is_active)
)
account_activation_token = TokenGenerator()
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignupForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password
"""
Django settings for project.
import os
from pathlib import Path
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.DEBUG: 'alert-secondary',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# 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',
'dashboard.apps.DashboardConfig',
'user.apps.UserConfig',
'crispy_forms',
]
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 = 'inventoryproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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 = 'inventoryproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME': 'inventory',
# 'USERNAME': 'root',
# 'HOST': 'localhost',
# 'PORT': 3306,
# 'PASSWORD': '', # Your Password
# }
# }
#
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
CRISPY_TEMPLATE_PACK = 'bootstrap4'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = (BASE_DIR/"media/")
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
STATIC_ROOT = (BASE_DIR/"asert/")
LOGIN_REDIRECT_URL = 'dashboard-index'
LOGIN_URL = 'user-login'
# if DEBUG:
# EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
#
# else:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com',
EMAIL_HOST_USER = 'clients.red#gmail.com',
EMAIL_HOST_PASSWORD = 'password1',
EMAIL_PORT = 587
def register(request):
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user = form.save()
group = Group.objects.get(name='Customers')
user.groups.add(group)
current_site = get_current_site(request)
mail_subject = "Activate your account."
message = {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
}
message = get_template('acc_active_email.html').render(message)
to_email = form.cleaned_data.get('email')
print(to_email)
email = EmailMessage(mail_subject, message, to=[to_email])
email.content_subtype = "html"
import socket
socket.getaddrinfo('localhost', 25)
email.send()
error
TypeError at /register/
getaddrinfo() argument 1 must be string or None
Request Method: POST
Request URL: http://127.0.0.1:8000/register/
Django Version: 3.2
Exception Type: TypeError
Exception Value:
getaddrinfo() argument 1 must be string or None
Exception Location: C:\Users\ACME\AppData\Local\Programs\Python\Python39\lib\socket.py, line 954, in getaddrinfo
Python Executable: C:\Users\ACME\Desktop\inventory\inventory\real\Scripts\python.exe
Python Version: 3.9.10
Python Path:
['C:\\Users\\ACME\\Desktop\\inventory\\inventory',
'C:\\Users\\ACME\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\ACME\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\ACME\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\ACME\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\ACME\\Desktop\\inventory\\inventory\\real',
'C:\\Users\\ACME\\Desktop\\inventory\\inventory\\real\\lib\\site-packages']
Server time: Sat, 11 Jun 2022 18:13:49 +0000
Well, you know that , changes string to tuple? Just delete it :)
EMAIL_HOST = 'smtp.gmail.com',
EMAIL_HOST_USER = 'clients.red#gmail.com',
EMAIL_HOST_PASSWORD = 'password1',
# should look like this:
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'clients.red#gmail.com'
EMAIL_HOST_PASSWORD = 'password1'
And I think you will be good to go (I assume that you created app_password in Google account as changes came since 01.06 this year and it's not account passowrd)

Seperate Resource Server(Django-oauth-toolkit) - 403 Forbidden Error(If RESOURCE_SERVER_INTROSPECTION_CREDENTIALS is used)

I run into an issue not sure if this is a bug. Any help would be appreciated.
Some context:
Authorization Grant Type is Resource Owner Password Credentials where the Client Type is "confidential".
I used csrf_exempt decorator and protected_resource decorator for a view response function in the resource server.
Django REST Framework is used.
Django REST Framework v3.12.4 and Django OAuth Toolkit v1.5.0 are used.
I referred to the official documentation: https://django-oauth-toolkit.readthedocs.io/en/latest/resource_server.html
Testing Setup is similar to the Referenced Article using two different ports: https://medium.com/#sarit.r/simple-seperate-auth-server-and-resource-server-36a7813ea8aa
Auth Server: https://github.com/pathumveyron24/Django-Auth-Server
Resource Server: https://github.com/pathumveyron24/Django-Resource-Server
Auth Server Settings File:
"""
Django settings for auth_server project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
from .config import DB_ENGINE, DB_NAME, DB_USERNAME, DB_PASSWORD, DB_HOST, DB_PORT, TIME_ZONE
# 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-h6pzc5%ovv^&5o5dg0z&e8k$7y*)fufjz%2s3t(*jick#u_u9g'
# 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',
'corsheaders',
'oauth2_provider', # OAuth2
'rest_framework', # API
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'oauth2_provider.middleware.OAuth2TokenMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# -- Set up DRF to use OAuth2
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
'rest_framework.authentication.SessionAuthentication', # To keep the Browsable API
),
# 'DEFAULT_PERMISSION_CLASSES': (
# 'rest_framework.permissions.IsAuthenticated',
# ),
}
OAUTH2_PROVIDER = {
# token expiration time
'ACCESS_TOKEN_EXPIRE_SECONDS': 60 * 30,
# this is the list of available scopes
'SCOPES': {
'users': 'user details',
'read': 'Read scope',
'write': 'Write scope',
'groups': 'Access to your groups',
'introspection': 'introspection',
},
}
ROOT_URLCONF = 'auth_server.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 = 'auth_server.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',
'ENGINE': DB_ENGINE,
'NAME': DB_NAME,
'USER': DB_USERNAME,
'PASSWORD': DB_PASSWORD,
'HOST': DB_HOST,
'PORT': DB_PORT,
}
}
# 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 = TIME_ZONE
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/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ORIGIN_ALLOW_ALL = True
Resource Server Settings File:
"""
Django settings for resource_server project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
from .config import DB_ENGINE, DB_NAME, DB_USERNAME, DB_PASSWORD, DB_HOST, DB_PORT, TIME_ZONE, BASE_URL, CLIENT_ID, CLIENT_SECRET
# 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-gx4j%)k)sdyb#dk!&1uwpyo867v&gv-g-y)r0)#h=ff4e0z)(t'
# 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',
'db_models.apps.DbModelsConfig',
'property.apps.PropertyConfig',
'corsheaders',
'oauth2_provider', # OAuth2
'rest_framework', # API
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'oauth2_provider.middleware.OAuth2TokenMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# -- Set up DRF to use OAuth2
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
'rest_framework.authentication.SessionAuthentication', # To keep the Browsable API
),
# 'DEFAULT_PERMISSION_CLASSES': (
# 'rest_framework.permissions.IsAuthenticated',
# ),
}
OAUTH2_PROVIDER = {
# token expiration time
# 'ACCESS_TOKEN_EXPIRE_SECONDS': 60 * 30,
# this is the list of available scopes
# 'SCOPES': {
# 'read': 'Read scope',
# 'write': 'Write scope',
# 'introspection': 'Introspect token scope',
# },
'RESOURCE_SERVER_INTROSPECTION_URL': BASE_URL,
'RESOURCE_SERVER_INTROSPECTION_CREDENTIALS': (CLIENT_ID, CLIENT_SECRET),
}
ROOT_URLCONF = 'resource_server.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 = 'resource_server.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',
'ENGINE': DB_ENGINE,
'NAME': DB_NAME,
'USER': DB_USERNAME,
'PASSWORD': DB_PASSWORD,
'HOST': DB_HOST,
'PORT': DB_PORT,
}
}
# 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 = TIME_ZONE
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/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ORIGIN_ALLOW_ALL = True
For resource server,
register application as "Resource owner password-based"
This will give you client id and secret.
Use above client id and secrets as username and password with "http basic auth"
# At resource server, to check token
import requests
from requests.auth import HTTPBasicAuth
introspect_url = '<auth-server-host-here>/o/introspect/'
introspect_data = {'token': access_token_here}
introspect_response = requests.post(introspect_url, data=introspect_data, auth=HTTPBasicAuth(resource_server_client_id_here, resource_server_client_secret_here))
Ref:
https://django-oauth-toolkit.readthedocs.io/en/latest/resource_server.html

django.db.utils.OperationalError: could not translate host name "postgis-container" to address

I am trying to build an image in django that will later be deployed on a digitalocean droplet with my own domain name. I am currently trying to get rid of an issue that I believe is affecting my progress in relation to my local postgis container. I have a container named: postgis-container in the network: awm. After I run:
python manage.py makemigrations
I get the error:
django.db.utils.OperationalError: could not translate host name "postgis-container" to address: Temporary failure in name resolution
I was told by my lecturer to use the network alias for the ALLOWED_HOSTS field in my settings.py but it didn't make any difference. I put a comment to the right hand side of the possible offending line.
settings.py
"""
Django settings for AdvancedWebMapping project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
import socket
from pathlib import Path
import docker_config
from whitenoise.storage import CompressedManifestStaticFilesStorage
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = docker_config.SECRET_KEY
# 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',
'django.contrib.gis',
'world',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'AdvancedWebMapping.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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 = 'AdvancedWebMapping.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'HOST': 'localhost',
'USER': 'docker',
'PASSWORD': 'docker',
'PORT': '25432',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = "/static/"
if socket.gethostname() =="matthew#acer":
DATABASES["default"]["HOST"] = "localhost"
DATABASES["default"]["PORT"] = 25432
else:
DATABASES["default"]["HOST"] = "postgis-container" # offending line?
DATABASES["default"]["PORT"] = 5432
# Set DEPLOY_SECURE to True only for LIVE deployment
if docker_config.DEPLOY_SECURE:
DEBUG = False
TEMPLATES[0]["OPTIONS"]["debug"] = False
ALLOWED_HOSTS = ['.matthewmawm.xyz', 'localhost', '209.97.133.19']
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CORS_ORIGIN_ALLOW_ALL = True
else:
DEBUG = True
TEMPLATES[0]["OPTIONS"]["debug"] = True
ALLOWED_HOSTS = ['*', ]
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
how I created the postgis container (docker):
sudo docker create --name postgis-container --network awm --network-alias postgis-container -t -p 25432:5432 -v name_of_volume:/var/lib/postgresql kartoza/postgis
My own mistake. My hostname was incorrect at socket.gethostname().

'NoneType' object is not iterable in Django project

I am getting "'NoneType' object is not iterable" error while I try to run my django app using " python manage.py runserver ip:port" whereas the same error does not occur if I use " python manage.py runserver 0.0.0.0:8000". I really need to get this work using my ip address.
Link to the error page 1 and
Link to the error page 2
What am I doing wrong?
This is how my settings.py looks like:
"""
Django settings for SimStudent project.
Generated by 'django-admin startproject' using Django 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 = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
#ALLOWED_HOSTS = ['0.0.0.0', '10.153.1.51', '127.0.0.1']
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'channels',
'chat',
'django_tables2',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'SimStudent'
]
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 = 'SimStudent.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'SimStudent.context_processor.tutor_tutee_session_info',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'SimStudent.wsgi.application'
ASGI_APPLICATION = 'SimStudent.routing.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
# 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'),
#}
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'simstudent_oz',
'USER': 'sim_tasmia',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '5433',
}
}
# 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, "static/")
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
And my context_processor.py looks like:
from django.shortcuts import get_object_or_404
from django.utils.safestring import mark_safe
import json
from chat.models import Session, TutorTuteeConversation
from django.core import serializers
from chat.models import Session
def tutor_tutee_session_info(request):
if 'session_id' in request.session:
session_id = request.session['session_id']
room_name = request.session['room_name']
print("inside context", session_id)
session = get_object_or_404(Session, pk=int(session_id))
chat_history = TutorTuteeConversation.objects.filter(session_id=int(session_id)).order_by('comment_time')
dict_chat_history = serializers.serialize("json", chat_history)
print("dict chat history inside context", dict_chat_history)
return {
"session_info": session,
"chat_history": mark_safe(json.dumps(dict_chat_history)),
"room_name": room_name,
}
Project directory structure is here
It happened to me and solved by making else returning an empty dict for example:
def test(request):
if condition:
return {"val":val}
else:
return {}

Static resources that get served over http don't get served over https

I wrote an application with Django that serves files built with Webpack. The application runs fine over http, but gives an error over https that I can't seem to find how to solve.
With debug set to True I get (for example)
GET https://localhost:8000/dist/bundles/css/main.f57231b6.css net::ERR_ABORTED 404 (Not Found)
with debug set to false I get
GET https://localhost:8000/dist/bundles/css/main.f57231b6.css net::ERR_ABORTED 500 (Internal Server Error)
for css and javaScript. The traceback on the server looks like this:
File "/Applications/anaconda3/lib/python3.6/wsgiref/handlers.py", line 137, in run
self.result = application(self.environ, self.start_response)
File "/Users/home/docs/Projects/Apprentice_Project/aws_env/lib/python3.6/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__
return super().__call__(environ, start_response)
File "/Users/home/docs/Projects/Apprentice_Project/aws_env/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 146, in __call__
response = self.get_response(request)
File "/Users/home/docs/Projects/Apprentice_Project/aws_env/lib/python3.6/site-packages/django/contrib/staticfiles/handlers.py", line 62, in get_response
return super().get_response(request)
File "/Users/home/docs/Projects/Apprentice_Project/aws_env/lib/python3.6/site-packages/django/core/handlers/base.py", line 81, in get_response
response = self._middleware_chain(request)
TypeError: 'NoneType' object is not callable
[01/Aug/2018 05:48:59] "GET /dist/bundles/css/main.f57231b6.css HTTP/1.1" 500 59
Can anyone tell me why I'm getting the NoneType error with https?
settings.py:
"""
Django settings for prentice project.
Generated by 'django-admin startproject' using Django 2.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
import environ
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# defining which variables django-environ should look for
env = environ.Env(
SECRET_KEY=str,
DB_HOST=(str, '127.0.0.1'),
DB_NAME=str,
DB_USER=str,
DB_PASSWORD=str,
DB_PORT=int
)
#Read environment variables
environ.Env.read_env(os.path.join(BASE_DIR, '.env.prod'))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
# Set to 'True' for dev environment
DEBUG = True
ALLOWED_HOSTS = ['localhost', 'prentice.us-east-1.elasticbeanstalk.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party apps
'webpack_loader',
'knox',
'sslserver',
# Custom apps
...
]
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',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'configuration.urls'
WSGI_APPLICATION = 'configuration.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
if 'RDS_DB_NAME' in os.environ:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['RDS_DB_NAME'],
'USER': os.environ['RDS_USERNAME'],
'PASSWORD': os.environ['RDS_PASSWORD'],
'HOST': os.environ['RDS_HOSTNAME'],
'PORT': os.environ['RDS_PORT'],
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': env('DB_NAME'),
'USER': env('DB_USER'),
'PASSWORD': env('DB_PASSWORD'),
'HOST': env('DB_HOST'),
'PORT': env('DB_PORT'),
}
}
#Substitute custom User model
AUTH_USER_MODEL = 'auth_api.User'
# Password validation
# https://docs.djangoproject.com/en/2.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',
},
]
# Rest framework settings
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',),
}
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Dawson'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/dist/'
STATIC_ROOT = 'dist'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "dist","bundles"),
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "dist", "bundles"), ],
'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',
],
},
},
]
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.prod.json'),
}
}
I think :
With debug turned off Django won't handle static files for you any more - your production web server (Apache or django-whitenoise ) should take care of that
I hope it helps :)