#07-Django Auth Login

Penjelasan

Sebelum nya kita telah membuat App “polls” menggunakan AdminLte, sekarang kita akan membuat App “pages” menggunakan AdminLTE. App akan berisi halaman Login, Welcome(harus dalam posisi login), dan Logout.

Sekenario

Jika authentikasi tidak terpenuhi, app akan mengarahkan ke page login, jika terpenuhi akan masuk ke halaman index, dan jika tombol logout di klik maka session akan direset dan user akan kembali ke halaman login

Membuat App pages:

python manage.py startapp pages

Views

pages/views.py

from django.shortcuts import get_object_or_404, render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model

@login_required(login_url='/login')
def index(request):
	return render(request, 'pages/index.html')

def login_view(request):
	if request.method=='POST':
		User = get_user_model()
		email = request.POST['email']
		username = User.objects.get(email=email).username
		password =  request.POST['password']
		user = authenticate(username=username, password=password)
		if user is not None:
			login(request, user)
			return redirect("/")
		else:
			return render(request, 'pages/login.html', {})
	return render(request, 'pages/login.html')
def logout_view(request):
	logout(request)
	return redirect('/login')

Perhatikan baris def login_view dan logout_view yang ditandai, penamaan tidak boleh sama dengan lib login dan logout yang diimport karena akan bentrok dengan fungsi login dan logout.

Fungsi @login_required(login_url=’/login’) sebelum def index menandakan halaman tersebut dapat dibuka hanya jika kondisi authenticate terpenuhi.

Route

Edit file pages/urls.py

from django.urls import path
from . import views

urlpatterns = [
	path('', views.index, name='index'),
	path('login', views.login_view, name='login'),
	path('logout', views.logout_view, name='logout'),
]

Template Login:

buat file pages/templates/pages/login.html

<!DOCTYPE html>
<html>
<head>
    {% load static %}
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>AdminLTE 3 | Log in</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="{% static '/plugins/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css' %}">
  <link rel="stylesheet" href="{% static '/plugins/icheck-bootstrap/icheck-bootstrap.min.css' %}">
  <link rel="stylesheet" href="{% static '/css/adminlte.min.css' %}">
  <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
</head>
<body class="hold-transition login-page">
<div class="login-box">
  <div class="login-logo">
    <a href="login"><b>Admin</b>LTE</a>
  </div>
  <div class="card">
    <div class="card-body login-card-body">
      <p class="login-box-msg">Sign in to start your session</p>

      <form action="login" method="post">
         {% csrf_token %}
        <div class="input-group mb-3">
          <input type="email" name="email" class="form-control" placeholder="Email">
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-envelope"></span>
            </div>
          </div>
        </div>
        <div class="input-group mb-3">
          <input type="password" name="password" class="form-control" placeholder="Password">
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-lock"></span>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-8">
            <div class="icheck-primary">
              <input type="checkbox" id="remember">
              <label for="remember">
                Remember Me
              </label>
            </div>
          </div>
          <div class="col-4">
            <button type="submit" class="btn btn-primary btn-block">Sign In</button>
          </div>
        </div>
      </form>

      <p class="mb-1">
        <a href="forgot-password.html">I forgot my password</a>
      </p>
      <p class="mb-0">
        <a href="register.html" class="text-center">Register a new membership</a>
      </p>
    </div>
  </div>
</div>
<script src="{% static '/plugins/jquery/jquery.min.js' %}"></script>
<script src="{% static '/plugins/bootstrap/js/bootstrap.bundle.min.js' %}"></script>
<script src="{% static '/js/adminlte.min.js' %}"></script>
</body>
</html>

Template Welcome

buat file pages/templates/pages/index.html

{% extends "base.html" %}
{% load static %} 
{% block content %}
<h1>Welcome</h1>
{% endblock %}

Struktur

├── myapp
├── pages
│   └── migrations
│   └── templates
|       ├── pages
│           ├── index.html
│           ├── login.html
│   ├── _init_.py
│   └── admin.py
│   └── apps.py
│   └── models.py
│   └── tests.py
│   └── urls.py
│   └── views.py

Testing

http://localhost:8000

Welcome Page

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>