How to authenticate User from mysql in django? - python

I want to implement login app. all the users information are in table named 'admin_users'. I am using mysql server by xampp.
when i am authenticating using user = authenticate(username=username,password=password)
On printing user I am getting None.
I am beginner in django and I could not find out whats wrong.
If I am doing AdminUsers.objects.all() I can print all the table information.
models.py
class AdminUsers(models.Model):
username=models.CharField(max_length=50)
firstname=models.CharField(max_length=50)
department=models.CharField(max_length=50)
mail=models.CharField(max_length=50)
id=models.IntegerField(primary_key=True)
password=models.CharField(max_length=200)
class Meta:
db_table="admin_users"
view.py
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username,password=password)
print(user)
return render(request,'AdminUsers/login.html')
my index.html contains simple forms with username and password.
settings.py
"""
Django settings for python_test project.
Generated by 'django-admin startproject' using Django 3.2.6.
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
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/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-j*uh&s1$j-'
# 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',
'myapp'
]
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 = 'python_test.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates'),
os.path.join(BASE_DIR,'app_kanri/templates/app_kanri/')
],
'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 = 'python_test.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydb',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
}
}
# 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 = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Not sure what your goal is with the AdminUsers model. The default django user model has flags like is_staff and is_superuser that you can use to seperate users and their permissions with regards to what they can access on the app.
Check out the docs on the user model here

You need to insert this in your settings: AUTH_USER_MODEL = 'AppName.AdminUsers' (replace AppName with the name of the app containing AdminUsers).
Your custom User model should inherit from AbstractUser to be compatible with the authentication system (right now it will not work):
class AdminUsers(AbstractUser):
department=models.CharField(max_length=50)
class Meta:
db_table='admin_users'
Now AdminUsers will inherit fields of AbstractUser (username, email, password, is_staff, ...), read this for details.
If you have already done migrations, you need to delete migrations of the default User model.
Note also that you should name the model 'AdminUser' and not 'AdminUsers'.

Related

Why getting settings.DATABASES is improperly configured. Please supply the ENGINE value.?

I have not written so much line just created a new database in setting.py and routers file in django project.
After this run following command in shell and every this goes well and a new file with name auth_db.db.sqlite3 create.
python manage.py migrate --database=auth_db
and
C:\Users\Admin\Desktop\project\assignment>python manage.py createsuperuser --database=auth_db
Username (leave blank to use 'admin'): admin
Email address: admin#gmail.com
Password:
Password (again):
The password is too similar to the username.
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
setting.py:-
"""
Django settings for assignment project.
Generated by 'django-admin startproject' using Django 3.2.3.
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
# 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-pg_xyl$21ofn1f5n*%vaymeniyubo3h^a2jmy&b$=83!gs+ni%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'assignment.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 = 'assignment.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {},
'auth_db': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'auth_db.db.sqlite3',
},
}
# 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 = 'UTC'
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'
DATABASE_ROUTERS = ['routers.db_routers.AuthRouter']
But when i tried to login in admin panel after running command python manage.py runserver i get error:
settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.

how can i use inbuilt django authentication and admin panel with MongoDB ? How can i make a connection like regular SQL in settings.py for mongoDB

connection with this settings works for CRUD methods but is incompatible for admin panel and authenticaion.if there is some way by which i can make connection with MongoDB like our regular POSTGRES,SQLITE eg with engine and port numbers in DATABASE Varibale in Settings.py file . Please Suggest
#
Settings.py
"""
Django settings for calculator project.
Generated by 'django-admin startproject' using Django 2.0.2.
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
DBDNAME='mydata'
_MONGODB_HOST='localhost'
_MONGODB_NAME='mydata'
_MONGODB_DATABASE_HOST = \
'mongodb://%s:%s#%s/%s'\
%('','',_MONGODB_HOST,_MONGODB_NAME)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR = os.path.join(BASE_DIR,'templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3gcc++w$zhw7k=4&)po*r4_sqc_u7vhbqt0vpdsx(&-#ob#taj'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'calc.apps.CalcConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'calculator.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_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 = 'calculator.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': '',
'NAME': '',
}
}
DBNAME='mydata'
_MONGODB_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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.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/2.0/howto/static-files/
STATIC_URL = '/static/'
#
models.py
from mongoengine import *
from calculator.settings import DBNAME
# Create your models here.
connect(DBNAME)
class information(Document):
number1 = StringField(max_length=120)
number2 = StringField(max_length=120)
values = StringField(max_length=120)
Result = StringField(max_length=120)
#
Please help me how should i proceed for admin panel and Authentication?
You can use django mongoengine. This is good for basic admin CRUD applications and will quickly get your work done.

Django ignores test database settings

I have an app deployed on pythonanywhere which runs fine. Problem is that when I want to run test django, my test database settings is completely ignored.
Each time I run test I get the following message.though.
Creating test database for alias 'default'...
Got an error creating the test database: (1044, "Access denied for user 'funnshopp'#'%' to database 'test_funnshopp$funn'")
Database name for the app is funnshopp$funn. It can be seen that django somehow always tries to create the test database by appending test_ to the database name. Never minding what I have in DATABASES settings
Below is my full settings file ( Test runs fine on my PC and I am using Django 2.0, though I started the project with Django 1.11)
"""
Django settings for funnshopp project.
Generated by 'django-admin startproject' using Django 1.11.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
from django.urls import reverse_lazy
from django.core.exceptions import ImproperlyConfigured
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def get_env_variable(var_name):
"""Get the environment variable or return exception"""
try:
return os.environ[var_name]
except KeyError:
error_msg = "Set the {} environment variable".format(var_name)
raise ImproperlyConfigured(error_msg)
ENV_ROLE = get_env_variable("ENV_ROLE")
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_env_variable("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
FUNN_PASS = False
if ENV_ROLE == "development":
DEBUG = True
FUNN_PASS = get_env_variable('FUNN_PASS')
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'asset',
'debit',
'communication',
'establishment',
'credit',
'personnel',
'relation',
'debug_toolbar',
'captcha',
'guardian',
'rules',
'coverage',
'django_extensions',
'pure_pagination',
'sorl.thumbnail',
'django_addanother',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend',
'rules.permissions.ObjectPermissionBackend',
)
MIDDLEWARE = [
'debug_toolbar.middleware.DebugToolbarMiddleware',
'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 = 'funnshopp.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 = 'funnshopp.wsgi.application'
INTERNAL_IPS = ('127.0.0.1', 'localhost')
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',
]
GOOGLE_RECAPTCHA_SITE_KEY = get_env_variable("GOOGLE_RECAPTCHA_SITE_KEY")
GOOGLE_RECAPTCHA_SECRET_KEY = get_env_variable("GOOGLE_RECAPTCHA_SECRET_KEY")
LOGIN_REDIRECT_URL = reverse_lazy('personnel:dashboard')
LOGIN_URL = reverse_lazy('personnel:login')
LOGOUT_URL = reverse_lazy('personnel:logout')
if ENV_ROLE == "development":
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_PORT = 587
EMAIL_HOST_USER = '***#gmail.com'
EMAIL_HOST_PASSWORD = '*******'
DEFAULT_FROM_EMAIL = '***#gmail.com'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DEPLOYMENT_PLATFORM = get_env_variable("DEPLOYMENT_PLATFORM")
if DEPLOYMENT_PLATFORM == "heroku-plus-local":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'funn',
'USER': 'postgres',
'PASSWORD': get_env_variable('FUNN_PASS'),
'HOST': 'localhost',
'PORT': 5432
}
}
else: # DEPLOYMENT_PLATFORM == "pythonanywhere"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'USER': 'funnshopp',
'NAME': 'funnshopp$funn',
'PASSWORD': get_env_variable('FUNN_PASS'),
'HOST': 'funnshopp.mysql.pythonanywhere-services.com',
'TEST':{
'ENGINE': 'django.db.backends.sqlite3', # for sqlite3
'NAME':'test.db',
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME':'funnshopp$test_default'
},
},
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Africa/Lagos'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
AUTH_USER_MODEL = 'personnel.Person'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
import django_heroku
django_heroku.settings(locals())
Below is the result of pip freeze
alabaster==0.7.10
Babel==2.5.1
beautifulsoup4==4.6.0
certifi==2017.11.5
chardet==3.0.4
colorama==0.3.9
coverage==4.4.2
dj-database-url==0.4.2
dj-static==0.0.6
Django==2.0.1
django-addanother==2.0.0
django-archive==0.1.5
django-braces==1.12.0
django-debug-toolbar==1.9.1
django-extensions==1.9.9
django-guardian==1.4.9
django-heroku==0.2.0
django-pure-pagination==0.3.0
django-recaptcha==1.3.1
django-toolbelt==0.0.1
django-webtest==1.9.2
docutils==0.14
funcsigs==1.0.2
gunicorn==19.7.1
idna==2.6
This is a common and correct behavior. Django when testing will always try to create new database, and you should never try to test you application on your live/production database.
Your tests should be constructed in a way, where you create your objects and then test their behavior. You are using postgres, on heroku and mysql on development server. If you want to use this databases to test you app, you have to add django user to you postgres/mysql with rights to create and delete databases/tables.
You can also avoid this by adding this setting to your settings.py (this is what I like to do when I do not use any other extensions and sqlite3 database is just enough. I run my tests by typing python manage.py test
if any([arg in sys.argv for arg in ['jenkins', 'test']]):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
}
}
I think you should change how you format your settings.py, you must not put if conditions inside it but use different settings based on the environment you are working on!
I recommend you to read this tutorial.
When you have the proper layout you can change the database in the different settings file ;)!
I solved the problem by reorganizing my settings file according to the pattern suggested here Recommended Django Project Layout.
Now my test runs fine on pythonanywhere.
Btw, I created a gist here which deals with the problems of virtual environments and layouts and how to handle virtual environment variables.
As you know, when you are running tests, Django isolates the changes made to the database. That is why it tries to create a database which is denied by the DB engine. You can either:
Create a database, grant access to the user and use --keepdb to run the tests
Or grant access to the DB user to create a database. Something like:
ALTER USER username CREATEDB;

django on production 500 server error for User related Model in Admin

I have deployed my Django(1.10) site on google compute engine, everything was working fine, but suddenly one of my model throwing 500 Server Error in admin.
I have googled around but couldn't find any solution.
All other models are displaying properly in django admin except only one and that's TaggedArticles model.
Idon't have changed anything in my site, what's can be wrong? as it happens suddenly to my site.
Here's my code:
settings.py:
"""
Django settings for brain project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# For a test push to trigger build from codeship.
# Second thing for CodeShip deployment push
# 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 = False
ALLOWED_HOSTS = ['127.0.0.1', '35.202.165.136', 'brainresearchtagging.com', 'www.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'
# DATABASES = {
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB_NAME',
'USER': 'DB_USERNAME',
'PASSWORD': 'DB_PASS',
'HOST': 'localhost',
'PORT': '',
}
}
#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
Here's Tagged Article's model:
choices = (
('yes', 'Yes'),
('no', 'No'),
('not sure', 'Not Sure'),
)
class TaggedArticle(models.Model):
user = models.ForeignKey(User, related_name='tagging')
email = models.EmailField(max_length=255)
category_fit = models.CharField(choices=choices, max_length=255)
article = models.ForeignKey(Article, related_name='articles')
link = models.URLField(max_length=255,)
relevant_feedback = models.TextField(blank=True)
category = models.CharField(max_length=255,)
created_at = models.DateTimeField(default=timezone.now, editable=False)
Here's admin.py:
class TaggedArticleAdmin(admin.ModelAdmin):
date_hierarchy = 'created_at'
fields = ['category_fit', 'article', 'link', 'relevant_feedback', 'category', 'user', 'email']
list_display = ['article', 'link', 'user', 'email', 'relevant_feedback']
list_filter = ['user', 'email']
model = TaggedArticle
admin.site.register(Tagged, TaggedArticleAdmin)
Update:
When i set debug=True, then it returns the following error:
ValueError at /admin/users/taggedarticle/
Database returned an invalid datetime value. Are time zone definitions for your database and pytz installed?
Request Method: GET
Request URL: http://www.brainresearchtagging.com/admin/users/taggedarticle/
Django Version: 1.10.5
Exception Type: ValueError
Exception Value:
Database returned an invalid datetime value. Are time zone definitions for your database and pytz installed?
Exception Location: /root/virEnv/lib/python3.6/site-packages/django/db/models/functions/datetime.py in convert_value, line 181
Python Executable: /root/virEnv/bin/python3.6
Python Version: 3.6.1
Python Path:
['/root/brain',
'/root/brain/brain',
'/root/virEnv/bin',
'/root/virEnv/lib/python36.zip',
'/root/virEnv/lib/python3.6',
'/root/virEnv/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6',
'/root/virEnv/lib/python3.6/site-packages',
'/root/virEnv/lib/python3.6/site-packages/odf',
'/root/virEnv/lib/python3.6/site-packages/odf',
'/root/virEnv/lib/python3.6/site-packages/odf',
'/root/virEnv/lib/python3.6/site-packages/odf',
'/root/virEnv/lib/python3.6/site-packages/odf',
'/root/virEnv/lib/python3.6/site-packages/odf',
'/root/virEnv/lib/python3.6/site-packages/odf']
Server time: Sat, 18 Nov 2017 11:55:01 +0000
This can be a mysql timezone issue. This is assuming that you have the required libraries from the error.
Check if the below value has been set in your /etc/mysql/my.cnf in [mysqld] section (after that tag). FI no, enter it and then reboot
`default-time-zone = 'UTC`'
Once you do this and it still doesnt work try flushing after doing the above.
mysql> flush tables;

Customizing Django User model yields error

I have created a custom User model inheriting from the Django one in models.py:
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
# Create your models here.
class User(AbstractUser):
pass
# triggered as soon as a new user is saved in the db
#receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
Following this link, I also add my app to INSTALLED_APP and change AUTH_USER_MODEL in settings.py:
"""
Django settings for WestMolkkyClubBackend project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 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
ALLOWED_HOSTS = ['192.168.0.12']
AUTH_USER_MODEL = 'WestMolkkyClubBackend.User'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework.authtoken',
'WestMolkkyClubBackend'
]
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 = 'WestMolkkyClubBackend.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 = 'WestMolkkyClubBackend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
I have also updated admin.py:
# Register your models here.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
admin.site.register(User, UserAdmin)
However I get the following errors when trying to migrate:
SystemCheckError: System check identified some issues:
ERRORS:
admin.LogEntry.user: (fields.E300) Field defines a relation with model 'WestMolkkyClubBackend.User', which is either not installed, or is abstract.
admin.LogEntry.user: (fields.E307) The field admin.LogEntry.user was declared with a lazy reference to 'WestMolkkyClubBackend.user', but app 'WestMolkkyClubBackend' doesn't provide model 'user'.
authtoken.Token.user: (fields.E300) Field defines a relation with model 'WestMolkkyClubBackend.User', which is either not installed, or is abstract.
authtoken.Token.user: (fields.E307) The field authtoken.Token.user was declared with a lazy reference to 'WestMolkkyClubBackend.user', but app 'WestMolkkyClubBackend' doesn't provide model 'user'.
Is there any mistake in my code?
I reset my project while using the custom User model during the first migration and it works. It was probably a project structure issue.

Categories