I am trying to authenticate the user using MySQL (running on XAMPP). However, the table in the database has been created, but when I manually add a user and password in the database and then try to authenticate, it shows invalid credentials.
The above task has been successfully done using sqlite3 .
Objectives to be achieved:
A) User authentication using MYSQL
B) Every time the user logs in, the name and date/time of the user login should be reflected in the database.
Here's my code:
models.py
from django.db import models
from datetime import datetime
from django.contrib.auth.models import AbstractUser
# Create your models here.
class Login(AbstractUser):
username = models.CharField(max_length=50,blank=False)
password = models.CharField(max_length=32)
def __str__(self):
return self.username
Views.py
from django.shortcuts import render
from first_app.forms import CmdForm #view after login
from django.http import HttpResponse, HttpResponseRedirect
#some imports
from django.urls import reverse
import csv
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
#from django.contrib.sessions import serializers
# Create your views here.
def login_view(request):
context = {}
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user:
login(request, user)
return HttpResponseRedirect(reverse('IP form'))
else:
messages.error(request,'Please provide valid credentials')
return render (request,"first_app/login.html", context)
else:
return render (request,"first_app/login.html", context)
@login_required
def user_logout(request):
if request.method == "POST":
auth.logout(request)
return HttpResponseRedirect(reverse('login'))
@login_required
def form_name_view(request): #view after login
if not request.user.is_authenticated:
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__)))
TEMPLATES_DIR = os.path.join(BASE_DIR,"templates")
STATIC_DIR = os.path.join(BASE_DIR,"static")
MEDIA_DIR = os.path.join(BASE_DIR,'media')
# 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 = 'm500^loxdxy2(q^lf4c(xwu%(-)qf4@-c=vc#f#ey!ooiy1zp('
# 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',
'first_app',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
#'django_session_timeout.middleware.SessionTimeoutMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'first_project.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 = 'first_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'automation_user',
'USER': 'root',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_USER_MODEL = 'first_app.Login' #custom user model
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 = [
STATIC_DIR,
]
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
LOGIN_URL = '/first_app/login'
SESSION_EXPIRE_SECONDS = 20
SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_COOKIE_AGE = 25
I have already gone through various blogs regarding this, but it was in vain.
Please suggest what changes I can make to achieve the above mentioned objective.
Thanks for the help!
Login.objects.create_user(username='test', password='SecretPassword')
and it should work. – Dalvtor Jul 29 '19 at 8:56Login.objects.create_user
as suggested, which will take care of hashing the password for you. – Daniel Roseman Jul 29 '19 at 11:52