10. Django Python – Autentikasi

django python bahasa indonesia

1. Halaman Login

Edit urls.py.

from django.contrib.auth.views import LoginView
urlpatterns = [
 …
 …
     path('siswa/login/', LoginView.as_view(), name='login'),
]

Buat folder registration di apps01. Buat file login.html di dalamnya.

{% extends "base.html" %}

{% block content %}
    <div class="container">
      <div class="row">
       <div class="col-md-4"></div>
       <div class="col-md-4">
         <div class="card">
           <div class="card-header">
             <b>Login</b>
           </div>
         <div class="card-body">
           <form method="POST">
             {% csrf_token %}

             {{ form.as_p }}
           <button class="btn btn-primary">Login</button>
           </form>
         </div>
        </div>
       </div>
       <div class="col-md-4"></div>
     </div>
    </div>
{% endblock content %}

Atur halaman redirect setelah login.

...
LOGIN_REDIRECT_URL = 'siswa'

2. Force Login

Atur login url.

...
LOGIN_URL = 'login'

Atur view mana yang harus dipaksa login terlebih dahulu sebelum diakses.

from django.contrib.auth.decorators import login_required
from django.conf import settings

@login_required(login_url=settings.LOGIN_URL)
def siswa(request):
  ...
  ...

3. Halaman Logout

Edit urls.py.

from django.contrib.auth.views import LoginView, LogoutView

urlpatterns = [
...
...
path('siswa/logout/', LogoutView.as_view(next_page='login'), name='logout'),
]

Lanjutkan Membaca Materi Lengkap


Leave a Reply

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

16 − eight =

This site uses Akismet to reduce spam. Learn how your comment data is processed.