Resolve AnonymousUser in Django - python

I have some problems when i create send email form using Django.
the problem is when i cliked for send button in contact form. I see this problem.
settings.py script here:
"""
Django settings for Connecting_System project.
Generated by 'django-admin startproject' using Django 4.0.6.
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
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-ix)p!+kk#f=47&2$%!7w98uflur_!n9o!tr77x3=r=4^r6b%bh'
# 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',
'login.apps.LoginConfig',
'Home.apps.HomeConfig',
'logout.apps.LogoutConfig',
'signup.apps.SignupConfig',
'contact.apps.ContactConfig',
]
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 = 'Connecting_System.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 = 'Connecting_System.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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
STATICFILES_DIRS = [
BASE_DIR / "static",
os.path.join(BASE_DIR, 'static'),
]
LOGIN_REDIRECT_URL = "/"
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOSTS_USER = '<youremail>#gmail.com'
EMAIL_HOSTS_EMAIL = '<youremail>#gmail.com'
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
views.py script here:
from http.client import HTTPResponse
from django.shortcuts import render, redirect
from django.core.mail import send_mail
#from Home import templates
from .forms import ContactForm
from django.template.loader import render_to_string
def contact(request):
# CONTACT FORM
if request.method == 'POST':
email = request.POST.get('email')
title = request.POST.get('title')
subject = request.POST.get('subject')
form_data = {
'email':email,
'title':title,
'subject':subject,
}
message = '''
New Message: {}
From: {}
'''.format(form_data['title'], form_data['email'])
send_mail(form_data['title'], message, '', ['<youremail>#gmail.com'], )
return HTTPResponse('Thank you for submitting the form ...')
return render(request, 'contact.html')
When I go to my google account to give access to my app for using my account from here google less secure
I see This setting is no longer available.

Simple spelling mistake.
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '<youremail>#gmail.com'
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
Host, not hosts, no plural here.
It gets rejected because the config is wrong.
It couldn't find an EMAIL_HOST_USER ->
Tries to connect to google with webmaster#localhost, as seen above ->
Obviously google rejects it.
Note
Gmail does not allow you to just send emails from any server. You have to allow it.
Have a look at the following tutorial if you run into any more issues: https://dev.to/abderrahmanemustapha/how-to-send-email-with-django-and-gmail-in-production-the-right-way-24ab

Related

sitemap.xml works on development but 404 errors on production

I've been following the documentation to add a sitemap to my website, everything works perfectly on development, once I upload to production, I have 404 errors as in sitemap can't be found. I checked the database on production to make sure the SITE_ID is the same as the pk of the site registered in database.
This is my installed app in settings.py
"""
Django settings for icerd project.
Generated by 'django-admin startproject' using Django 4.0.6.
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/
"""
import os
from pathlib import Path
from django.conf import global_settings
# Add custom languages not provided by Django
from django.conf import locale
from django.utils.translation import gettext_lazy as _
from icerd.productions import production_debug, production_secret_key, allowed_host, production_caches_location
# 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: don't run with debug turned on in production!
DEBUG = production_debug
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = production_secret_key
ALLOWED_HOSTS = ["*"] if DEBUG else allowed_host
AUTH_USER_MODEL = "registration.User"
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sites',
'django.contrib.sitemaps',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'homepage.apps.HomepageConfig',
'administration.apps.AdministrationConfig',
'registration.apps.RegistrationConfig',
]
# Multisite settings
SITE_ID = 1
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
# DataFlair #Caching Middleware
# 'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.cache.FetchFromCacheMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'registration.middleware.ActiveUserMiddleware',
]
ROOT_URLCONF = 'icerd.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 = 'icerd.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',
},
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
if DEBUG:
STATICFILES_DIRS = [
BASE_DIR / "static",
]
if not DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = 'static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = 'media/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Message storage
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
# Number of seconds of inactivity before a user is marked offline
USER_ONLINE_TIMEOUT = 300
# Number of seconds that we will keep track of inactive users for before
# their last seen is removed from the cache
USER_LASTSEEN_TIMEOUT = 60 * 60 * 24 * 7
# Caches settings
CACHES_LOCATION = production_caches_location
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': CACHES_LOCATION,
}
}
# Email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '*********'
EMAIL_HOST_PASSWORD = '********'
EMAIL_USE_TLS = True
EMAIL_SUBJECT_PREFIX = ""
EMAIL_USE_LOCALTIME = True
ADMINS = [
('Admin', 'example#gmail.com'),
]
MANAGERS = [
('Admin', 'example#gmail.com'),
]
# Language translation settings
EXTRA_LANG_INFO = {
'cr-ht': {
'bidi': False, # right-to-left
'code': 'cr-ht',
'name': 'Haitian Creole',
'name_local': "Kreyòl",
},
}
LANG_INFO = dict(locale.LANG_INFO, **EXTRA_LANG_INFO)
locale.LANG_INFO = LANG_INFO
LANGUAGES = (
('cr-ht', _('Kreyòl')),
('fr', _('Français')),
('en', _('English')),
)
# Languages using BiDi (right-to-left) layout
LANGUAGES_BIDI = global_settings.LANGUAGES_BIDI + ["cr-ht"]
LOCALE_PATHS = (
os.path.join(BASE_DIR / 'locale'),
)
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'fr'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Extra deployment parameters
if not DEBUG:
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_PRELOAD = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_COOKIE_AGE = 900 # 15 minutes
LOGIN_URL = '/login/'
LOGOUT_REDIRECT_URL = LOGIN_URL
# The number of seconds a password reset link is valid for (in second)
PASSWORD_RESET_TIMEOUT = 3600 # 1 hour
and this is my urls.py (root project where settings.py file is)
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.contrib.sitemaps.views import sitemap
from django.urls import path, include
from icerd import settings
from icerd.sitemaps import StaticViewSitemap
admin.site.site_header = "ICERD' website Administration"
admin.site.site_title = 'Administration'
admin.site.index_title = 'ICERD'
sitemaps = {
'static': StaticViewSitemap,
}
urlpatterns = [
path('i18n/', include('django.conf.urls.i18n')),
path('admin/', admin.site.urls),
path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap'),
path('', include('homepage.urls')),
path('registration/', include('registration.urls')),
path('administration/', include('administration.urls')),
path('reset_password/', auth_views.PasswordResetView.as_view(template_name="password/reset_password.html"),
name='reset_password'),
path('reset_password_sent/',
auth_views.PasswordResetDoneView.as_view(template_name="password/reset_password_sent.html"),
name='password_reset_done'),
path('reset/<uidb64>/<token>',
auth_views.PasswordResetConfirmView.as_view(template_name="password/reset_password_form.html"),
name='password_reset_confirm'),
path('reset_password_complete/',
auth_views.PasswordResetCompleteView.as_view(template_name="password/reset_password_done.html"),
name='password_reset_complete'),
]
if settings.DEBUG:
urlpatterns += static(
settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT
)
and this is my sitemaps.py (also in root, where settings.py is)
# sitemaps.py
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
class StaticViewSitemap(Sitemap):
priority = 0.5
changefreq = 'weekly'
def items(self):
return [
'homepage:homepage',
'homepage:get_logo',
'homepage:about_us',
'homepage:login',
'homepage:logout',
]
def location(self, item):
return reverse(item)
After all those, I made sure to run migrations, go to django admin and replace 'example.com' in sites' table.
If I run the same code on my computer, everything works fine, production doesn't work.
I use a debian vps to host my website using nginx and gunicorn.
Try adding this line to your nginx server block
rewrite ^/(.*)/$ /$1 permanent;
If it helps this means your browser is trying to access "/sitemap.xml/" (not "/sitemap.xml")

Generating token in django

I'm very new to django. I'm working on resetting the password with PasswordResetView. I've made all the necessary configurations. All the views are working properly(reset,done,confirm,complete) but the email is not being sent. I'm using file based method. The mail content is also stored in a text file successfully.
The text file
MIME-Version: 1.0
Content-Transfer-Encoding: 8bit
Subject: Password reset on 127.0.0.1:8000
From: webmaster#localhost
To: user1991#gmail.com
Date: Fri, 08 May 2020 13:07:44 -0000
Message-ID:
<158894326451.7060.3441580324173819052#DESKTOP-G46QTJT.localdomain>
You're receiving this email because you requested a password reset for your user account at 127.0.0.1:8000.
Please go to the following page and choose a new password:
http://127.0.0.1:8000/accounts/profile/reset-password/confirm/Ng/5gb-4468fc4f5f5c9ad67d90/
Your username, in case you’ve forgotten: test#5
Thanks for using our site!
The 127.0.0.1:8000 team
-------------------------------------------------------------------------------
But i didn't received the mail. Hoping for a solution. Atleast I want to know how to generate the one time url alone like the one django created automatically.
settings.py
"""
Django settings for tutorial project.
Generated by 'django-admin startproject' using Django 3.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!ku^2ct1u^jmk3+_8emila*#r2(9)avhsgf1#rnfhxb=30^4bp'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'accounts',
'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',
'tutorial.middleware.LoginRequiredMiddleware',
]
ROOT_URLCONF = 'tutorial.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 = 'tutorial.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
LOGIN_REDIRECT_URL = '/accounts/profile'
LOGIN_URL = '/accounts/login/'
LOGIN_EXEMPT_URLS = [
r'accounts/register',
]
EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend"
EMAIL_FILE_PATH = os.path.join(BASE_DIR, "sent_emails")
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'projectkesamad#gmail.com'
EMAIL_HOST_PASSWORD = 'Kesavan#pro'
urls.py
from django.urls import path, reverse_lazy, reverse
from . import views
from django.contrib.auth.views import (
LoginView,LogoutView,PasswordResetView,PasswordResetDoneView,PasswordResetConfirmView,PasswordResetCompleteView
)
app_name='accounts'
urlpatterns=[
path('',views.home,name='accounts_home_page'),
path('login/',LoginView.as_view(template_name='accounts/login.html'),name='login_page'),
path('logout/',LogoutView.as_view(template_name='accounts/logout.html'),name='logout_page'),
path('register/',views.registration,name='register_page'),
path('profile/',views.profile,name='profile'),
path('profile/edit_profile/',views.edit_profile,name='edit-profile'),
path('profile/change-password/',views.change_password,name='edit-profile'),
path('profile/reset-password/',PasswordResetView.as_view(template_name='accounts/reset_password.html',success_url = reverse_lazy('accounts:password_reset_done')),name='password_reset'),
path('profile/reset-password/done/',PasswordResetDoneView.as_view(),name='password_reset_done'),
path('profile/reset-password/confirm/<uidb64>/<token>/',PasswordResetConfirmView.as_view(success_url = reverse_lazy('accounts:password_reset_complete')),name='password_reset_confirm'),
path('profile/reset-password/complete/',PasswordResetCompleteView.as_view(),name='password_reset_complete'),
]
The above code is working as it is expected. The filebased Email_Backend is used to store emails in local directory instead of actually sending this to your email.
If you are trying to receive email in your gmail account, change your backend settings to django.core.mail.backends.smtp.EmailBackend
Make sure that SMTP congifuration of your gmail account is alright and it allows access to django: https://support.google.com/accounts/answer/6010255?hl=en
your settings.py should look like this:
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_HOST_USER = "xyz#gmail.com" # enter valid email address of which the smtp settings your configured
EMAIL_HOST_PASSWORD = "yourpassword"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
The above solutions should work but you can also send email by send_mail
subject = 'Thank you for registering to our site'
message = 'this is a test message'
email_from = 'xyz#gmail.com'
recipient_list = ['reciever#gmail.com', ]
connection = [
'xyz#gmail.com',
'mypassword',
False,
]
send_mail(subject, message, email_from, recipient_list, connection)
for this you will have to import send_mail: https://docs.djangoproject.com/en/3.0/topics/email/

Issue creating instance of Django model when model uses datetime?

I am currently making a project in Django that has two models: Cards and Articles. Both cards and articles have a manager that should allow me to quickly instantiate instances of the class. For cards I have the following:
class CardsManager(models.Manager):
def create_card(self, card_name, geography, player, typestatus, _weighted_strength = 0):
card = self.update_or_create(card_name=card_name, geography=geography, player=player, typestatus=typestatus)
return card
This manager works smoothly and I have no issue uploading cards. However, my article manager is a different story. This is my article manager.
class ArticleManager(models.Manager):
def create_article(self, title, body, cardvar, source, datetime, readthrough, author):
article_item = self.update_or_create(title=title, body=body, card=cardvar, source=source, entry_date_time=datetime, read_through=readthrough, cardvar__card_name=cardvar, author=author)
return article_item
When I try to upload an article however, say in the following fashion:
article_entry = Article.objects.create_article('title', 'empty body', 'test_card_var', 'The_Source', '2019-12-30 02:03:04', 0, 'author')
I get the following error in my Powrshell when I simply attempt 'python manage.py runserver': LookupError: No Installed app with label 'admin'.
When I attempt to run 'python manage.py makemigrations' I get another long error message whose last line is 'django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.'
I think the issue may have to do with something related to either 1) entry_date_time being a datetime object and passing a string (though I honestly am not sure how I'd pass a datetime object, what do they even look like) or b) the fact that cardvar is a ForeignKey pointing at the Cards model, which may not be allowed in an upload?
I really had no issues with uploading Cards but Articles has given serious issues. If anyone could help me resolve this issue it would be greatly appreciated, I'm still relatively new with Django and coding in general.
EDIT:
My Settings.py looks as follows:
"""
Django settings for newspaper_project 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
#import django_heroku
#import psycopg2
#import dj_database_url
#import dotenv
#import psycopg2
#import dj_database_url, psycopg2
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#DATABASE_URL = os.environ['DATABASE_URL']
#conn = psycopg2.connect(DATABASE_URL, sslmode='require')
# 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 = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#3rd party
'crispy_forms', #new
#Local
'users.apps.UsersConfig',
'pages.apps.PagesConfig',
'articles.apps.ArticlesConfig', #new
]
TIME_ZONE = 'America/New_York' #new
USE_TZ = True #TESTING THIS OUT
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 = 'newspaper_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], #new
'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 = 'newspaper_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
AUTH_USER_MODEL = 'users.CustomUser' #new
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #new
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = '**************************************'
EMAIL_PORT = 587
EMAIL_USE_TILS = True

Django on Production for POST request throws Server Error(500) on compute engine

I have deployed my Django 1.10 with python 3.6 Project on Google compute engine when I have changed Debug = True in my settings.py to Debug = False it throws Server Error (500) on one of my post requests.Even other post requests like signup are working fine.
When I stop gunicorn process and re-run it again then this POST works for few hours and again start throwing Server Error(500).
How can I solve this issue as I'm using Django 1.10.5, Python 3.6 on Compute Engine?
Help me, please!
Thanks in Advance!
Here's my 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__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*************************'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'brainresearchtagging.com']
# INTERNAL_IPS = ['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',
'debug_toolbar',
'users',
'article',
'import_export',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'brain.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 = 'brain.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'DB_NAME',
'USER': 'DB_USER',
'PASSWORD': 'DB_PASS',
'HOST': 'IP',
'PORT': '5432',
}
}
#Static Storage
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
# 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_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/assets/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'assets'), ]
# Authentication
LOGIN_URL = 'users:login'
LOGIN_REDIRECT_URL = 'users:dashboard'
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = os.path.join(BASE_DIR, 'emails')
# Django Import-Export
IMPORT_EXPORT_USE_TRANSACTIONS = True
And Here's my view which throws Server Error(5005):
From views.py:
class TagView(LoginRequiredMixin, generic.CreateView):
form_class = forms.TagForm
def post(self, request, *args, **kwargs):
if request.method == 'POST':
post_data = request.POST.copy()
post_data.update({'user': request.user.pk})
form = forms.TagForm(post_data)
if form.is_valid():
print(form.errors)
tag = form.save(commit=False)
tag.user = request.user
tag.email = request.user.email
tag.save()
else:
return HttpResponse(form.errors, status=400)
return HttpResponseRedirect(reverse_lazy('users:dashboard'))
As discussion above from comments, you can put exception handling in code and put logger in the code. For example:
import logging
class TagView(LoginRequiredMixin, generic.CreateView):
form_class = forms.TagForm
def post(self, request, *args, **kwargs):
try:
post_data = request.POST.copy()
post_data.update({'user': request.user.pk})
form = forms.TagForm(post_data)
if form.is_valid():
tag = form.save(commit=False)
tag.user = request.user
tag.email = request.user.email
tag.save()
else:
return HttpResponse(form.errors, status=400)
return HttpResponseRedirect(reverse_lazy('users:dashboard'))
except Exception as exp:
logging.error(exp) # For python 3
return HttpResponse(exp, status=400)
And view the error logs using log monitoring tool like this blog mentioned: https://cloud.google.com/python/monitor-and-debug/logging-application-events
Details about exception handling: https://docs.python.org/3/tutorial/errors.html
*** As per discussion in the comments in the answer, the problem resides in ALLOWED_HOSTS. Setting ALLOWED_HOSTS=['*'] or Setting the IP of the Server in Allowed Host solved the issue.

Asynchronious email sending using celery doesn't work

I'm trying to make Django not to wait until an email is sent. I've decided to use Celery to do that. Unfortunately I can't figure out how to make it work asynchronously.
I've created a file tasks.py:
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from .notifications import CustomerNotifications
from celery import shared_task
#shared_task
def prereservation_has_been_confirmed(reservation):
CustomerNotifications.prereservation_has_been_confirmed(reservation)
The CustomerNotifications.prereservation_has_been_confirmed(reservation) method sends an email to customer.
Email sending works but it still waits until the email is sent. (the view is called by AJAX).
Do you know what to do?
EDIT
This is how the function is being called:
#csrf_exempt
def reservation_confirm(request):
if request.method == 'POST':
reservation_id = request.POST.get('reservation_id', False)
reservation = get_object_or_404(dolava_models.Reservation, id=reservation_id)
reservation.confirmed = True
reservation.save()
tasks.prereservation_has_been_confirmed(reservation)
return JsonResponse({})
raise Http404(u'...')
I tried tasks.prereservation_has_been_confirmed.delay(reservation) but it returns that connection has been refused.
SETTINGS.PY - added BROKER_URL = 'django://', 'kombu.transport.django' and migrated.
# -*- coding: utf-8 -*-
"""
Django settings for dolava project.
Generated by 'django-admin startproject' using Django 1.9.7.
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
# 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 = 'secret_key'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'admin_interface',
'flat',
'colorfield',
'django.contrib.admin',
'django.contrib.auth',
# 'djcelery_email',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dolava_app',
# 'constance',
# 'constance.backends.database',
'solo',
'django_extensions',
'django_tables2',
'django_countries',
'kombu.transport.django'
]
MIDDLEWARE_CLASSES = [
'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 = 'dolava.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',
'django.core.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'dolava.wsgi.application'
BROKER_URL = 'django://'
# 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/'
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
# CELERY_ALWAYS_EAGER = True
# SMTP SETTINGS
# EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_BACKEND = "mailer.backend.DbBackend"
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'xxx#gmail.com'
EMAIL_HOST_PASSWORD = 'pass'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
[Following the comments] your task was correctly sent to the broker (to the database in your case) you can probably check that your pending task is there.
you don't see anything in the console because you must launch a celery worker that will read all the pending tasks on the broker and will execute them. have you started the worker process? there you'll see the tasks that are being called and the results or traceback if something fails
You are not making async call to prereservation_has_been_confirmed() in order to delay function execution use prereservation_has_been_confirmed.delay(...)
#csrf_exempt
def reservation_confirm(request):
if request.method == 'POST':
reservation_id = request.POST.get('reservation_id', False)
reservation = get_object_or_404(dolava_models.Reservation, id=reservation_id)
reservation.confirmed = True
reservation.save()
# change HERE, you are calling your function directly not asynchronously
tasks.prereservation_has_been_confirmed(reservation)
# change to below
# tasks.prereservation_has_been_confirmed.delay(reservation)
return JsonResponse({})
raise Http404(u'...')
Other than that, you have not configured Celery properly to use in Django app.
See Django celery first steps

Categories

Resources