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
Related
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
I'm developing a Django application to track crypto assets, what Im looking to do is, to take a snapshot of the user total value every 5 Days (X time).
What i did for now:
core/celery.py
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from celery.schedules import crontab
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
app = Celery('core')
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
app.conf.beat_schedule = {
'print': {
'task': 'app.tasks.test',
'schedule': 15
},
}
app.conf.timezone = 'UTC'
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
#app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
core/settings.py:
# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""
import os
from decouple import config
from unipath import Path
import dj_database_url
import django
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = Path(__file__).parent
CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY', default='S#perS3crEt_1122')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', default=True, cast=bool)
# load production server from .env
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'e6b5f240dedb.ngrok.io',
config('SERVER', default='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',
'django.contrib.sites',
'django_celery_beat',
'chartjs',
"allauth",
"allauth.account",
"allauth.socialaccount",
"allauth.socialaccount.providers.google",
'app'
]
SITE_ID = 2
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 = 'core.urls'
LOGIN_REDIRECT_URL = "/" # Route defined in app/urls.py
LOGOUT_REDIRECT_URL = "/login" # Route defined in app/urls.py
TEMPLATE_DIR = os.path.join(
CORE_DIR, "core/templates") # ROOT dir for templates
SOCIALACCOUNT_PROVIDERS = {
'google': {
'SCOPE': [
'profile',
'email',
],
'AUTH_PARAMS': {
'access_type': 'online',
}
}
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'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 = 'core.wsgi.application'
# Celery Configuration Options
CELERY_TIMEZONE = "Europe/Sofia"
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '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',
},
]
# Cron jobs
# 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
#############################################################
# SRC: https://devcenter.heroku.com/articles/django-assets
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
os.path.join(CORE_DIR, 'core/static'),
)
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
#############################################################
#############################################################
app/tasks.py:
from __future__ import absolute_import, unicode_literals
from celery import shared_task
#shared_task
def test():
print("Message for me and for you")
and right after, when i execute
celery -A core worker -l info
i get error "celery: command not found"
Note: I did python manage.py migrate, and Im able to see new table in admin page.
When i run the project, no error is showing but the task is not executing.
Thanks!
It seems you haven't installed Django Celery on your server, run
pip install django-celery
then restart everything again
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/
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
I keep getting this error when i try to import my models.py file into views.py or any of the other python script in my App directory,
I have the SECRET_KEY in settings.py and also add app in the list of INSTALLED_APPS,
wsgi.py contains
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings') # I replaced my project name
manage.py also contains
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')
I have checked through other people's installations in StackOverflow posts. My code works but importing models just break it
I use this command to import my class
from app_name.models import subscribers
and subscribers is defined thus
class subscribers(models.Model):
name = models.CharField('Name', max_length=120)
email = models.CharField('Email', max_length=120)
access_token = models.TextField()
expires_in = models.DateTimeField('token expiry date')
I have already executed makemigrations and migrate commands but being a newbie I don't know where else to look. Please save a soul it's been 3 days
thanks.
below is my settings.py
"""
Django settings for ps project.
Generated by 'django-admin startproject' using Django 2.2.6.
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
from oauth_outlook.views import gettoken
# 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='l!u#h#an5lj%b))=fzhv6r-3ay1&29=ls0*o1_^dxi(01x$et#'
#SECRET_KEY = os.environ.get("SECRET_KEY", "l!u#h#an5lj%b))=fzhv6r-3ay1&29=ls0*o1_^dxi(01x$et#")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'oauth_outlook',
'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',
'lockdown.middleware.LockdownMiddleware',
]
ROOT_URLCONF = 'ps.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 = 'ps.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/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
LOCKDOWN_PASSWORDS = ('letmein', 'beta')
LOCKDOWN_VIEW_EXCEPTIONS = [
gettoken,
]
It looks like the following import is causing the problem:
from oauth_outlook.views import gettoken
Importing views or models in the settings can cause circular imports and lead to the SECRET_KEY error message even when it is set. I don’t like the way django-lockout is encouraging you to import views for the LOCKDOWN_VIEW_EXCEPTIONS setting.
I suggest you set LOCKDOWN_URL_EXCEPTIONS instead, then the import isn’t required.
LOCKDOWN_URL_EXCEPTIONS = (
r'^gettoken$', # replace with gettoken view
)