article

Thursday, May 5, 2022

Django Mysql User Authentication - Login, register and Logout

Django Mysql User Authentication - Login, register and Logout

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Register App myapp and
Connect to MySQL Database

devproject/settings.py
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
   
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\devproject>python manage.py makemigrations
C:\django\devproject>python manage.py migrate
Creating View
myapp/views.py
//myapp/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import logout
from django.shortcuts import HttpResponseRedirect
 
def signup(request):
    if request.user.is_authenticated:
        return redirect('/')
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('/')
        else:
            return render(request, 'signup.html', {'form': form})
    else:
        form = UserCreationForm()
        return render(request, 'signup.html', {'form': form})
  
def home(request): 
    return render(request, 'home.html')
  
 
def signin(request):
    if request.user.is_authenticated:
        return render(request, 'home.html')
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('/profile') #profile
        else:
            msg = 'Error Login'
            form = AuthenticationForm(request.POST)
            return render(request, 'login.html', {'form': form, 'msg': msg})
    else:
        form = AuthenticationForm()
        return render(request, 'login.html', {'form': form})
 
def profile(request): 
    return render(request, 'profile.html')
  
def signout(request):
    logout(request)
    return redirect('/')
devproject/urls.py
//devproject/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
    path('signin/',views.signin, name='signin'),
    path('signout/',views.signout, name='signout'),
    path('signup/',views.signup, name='signup'),
    path('profile/',views.profile, name='profile'),
]
myapp/templates/index.html
//myapp/templates/home.html
{% extends 'base.html' %}
 
{% block title %}Login{% endblock %}
 
{% block content %}
   <h2>Welcome!</h2>
   {% if user.is_authenticated %}
      Hi {{ user.username }}!
      <a href="/signout" class="btn btn-danger">Logout</a>
    {% else %}
      <a href="/signin" class="btn btn-primary"><span class="glyphicon glyphicon-log-in"></span>Login</a> 
      <a href="/signup" class="btn btn-success">Signup</a>
    {% endif %}
{% endblock %}
myapp/templates/base.html
//myapp/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}Django Mysql User Authentication - Login, register and Logout{% endblock %}</title>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
  <div class="container">
  <header>
    <h1>Django Mysql User Authentication - Login, register and Logout</h1>
  </header>
  <hr>
  <main>
    {% block content %}
    {% endblock %}
  </main>
  <hr>
  </div>
</body>
</html>
myapp/templates/login.html
//myapp/templates/login.html
{% extends 'base.html' %}
 
{% block title %}Login{% endblock %}
 
{% block content %}
  <h2>Login</h2> {{ msg }}
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-primary">Login</button>
  </form>
{% endblock %}
myapp/templates/signup.html
//myapp/templates/signup.html
{% extends 'base.html' %}
 
{% block content %}
  <h2>Sign up</h2>
  <form method="post">
    {% csrf_token %}
    {% for field in form %}
      <p>
        {{ field.label_tag }}<br>
        {{ field }}
        {% for error in field.errors %}
          <p style="color: red">{{ error }}</p>
        {% endfor %}
      </p>
    {% endfor %}
    <button type="submit" class="btn btn-success">Sign up</button>
  </form>
{% endblock %}
myapp/templates/profile.html
//myapp/templates/profile.html
{% extends 'base.html' %}
 
{% block title %}Login{% endblock %}
 
{% block content %}
   <h2>Welcome!</h2>
   {% if user.is_authenticated %}
      Hi {{ user.username }}!
      <a href="/signout" class="btn btn-danger">Logout</a>
    {% else %}
      <a href="/signin" class="btn btn-primary"><span class="glyphicon glyphicon-log-in"></span>Login</a> 
      <a href="/signup" class="btn btn-success">Signup</a>
    {% endif %}
{% endblock %}
Run : C:\django\devproject>python manage.py runserver

Related Post