Mini Wallet Bagian 6 - Django Model CRUD

Subscribe Dengan Account Google Untuk Membaca Artikel Tanpa Iklan !
Mini Wallet Bagian 6 - Django Model CRUD
Lenovo IdeaPad Slim 3 14ABR8 AMD Ryzen 5

Lenovo IdeaPad Slim 3 14ABR8 AMD Ryzen 5

Lenovo IdeaPad Slim 3 14ABR8 82XL0004ID - ABYSS BLUE = LENOVO SLIM 3 82XL007CID R5-7530U/8GB/512GB/14.0/WIN11+OHS/ABYSS BLUE, Lenovo IdeaPad Slim 3 14ABR8 82XL0005ID - ARCTIC GREY = LENOVO SLIM 3 82XL007BID R5-7530U/8GB/512GB/14.0/WIN11+OHS/ARCTIC GREY

Free Klik Disini !

Pada tutorial sebelumnya kita telah belajar tentang Django Session Login dan juga telah mempelajari bagaimana penggunaan decorator auth login di Django.

Di tutorial ini kita akan belajar CRUD menggunakan Django Model. Pastikan juga Anda telah mengikuti tutorial terkait dengan Django Model.

CRUD identik dengan perintah SQL yaitu CREATE, READ, UPDATE, DELETE.

Namun bagaimana penerepan CRUD pada django Framework ?

Untuk itu, yuks ... sama-sama belajar penerapan operasi CRUD pada Django Model.

Perhatikan relational diagram berikut ini:

ewallet diagram ewallet diagram // source of halovina

Dari gambar diatas ada sebuah table dengan nama account_type, table ini bisa kita sebut sebagai table master.

A) Template Account Type


Buat folder dengan nama account, kemudian buat file dengan nama index.html

{% extends 'base.html' %}
{% block content %}
<h2>Tipe Akun</h2>
<div class="col-md-12 order-md-2 mb-4">
<button type="button" class="btn btn-secondary">Tambah Data</button>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Nama Account</th>
<th>Slug</th>
<th>Created Date</th>
<th>Updated Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
Action
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li><a class="dropdown-item" href="#">Edit</a></li>
<li><a class="dropdown-item" href="#">Delete</a></li>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
</div>

{% endblock %}

B) HTML Form Account Type


Buat file dengan nama form.html, simpan di direktori templates/account.

{% extends 'base.html' %}
{% block content %}
<h2>{{h_title}}</h2>
<div class="col-md-12 order-md-2 mb-4">
<form action="" method="post">
<div class="mb-3 mt-3">
<label for="account_type_name" class="form-label">Tipe Akun:</label>
<input type="text" class="form-control" id="account_type_name" placeholder="Tipe Akun" name="account_type_name">
</div>
<button type="submit" class="btn btn-primary">SUBMIT</button>
</form>
</div>
{% endblock %}

C) Django Class Based View Account Type


Sekarang buka file views.py di app account, buat class dengan nama AccountType().

from django.views.generic import TemplateView
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

# Create your views here.

class AccountType(TemplateView):
template_name = 'account/index.html'

@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context

D) Django Model Create


Buat sebuah class dengan nama AccountTypeCreate()

class AccountTypeCreate(TemplateView):
template_name = 'account/form.html'

@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['h_title'] = "Tambah Data"
return context

Kemudian tambahkan method post pada class AccountTypeCreate()

from .models import (AccountType as  AccountTypeModel)
from django.http import HttpResponseRedirect
from django.utils.text import slugify
from django.contrib import messages

.......
def post(self, *args, **kwargs):
try:
typeName = self.request.POST.get('account_type_name')
AccountTypeModel(
type_name= typeName,
slug = slugify(typeName)
).save()
messages.success(self.request, "Tambah data success")
except Exception as e:
messages.error(self.request, str(e))
return HttpResponseRedirect('/acc/account-type')

E) Django Model Read


Modifikasi class AccountType(), tambahkan kode berikut:

context['acc'] = AccountTypeModel.objects.all().order_by('-id')


Kode diatas berfungsi untuk mengambil semua data yang ada di class model AccountType()

Kemudian tampilkan data di index.html

{% extends 'base.html' %}
{% load humanize %}
{% block content %}
<h2>Tipe Akun</h2>
<div class="col-md-12 order-md-2 mb-4">
<a href="/acc/account-type/create">
<button type="button" class="btn btn-secondary">Tambah Data</button>
</a>

<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Nama Account</th>
<th>Slug</th>
<th>Created Date</th>
<th>Updated Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for x in acc %}
<tr>
<td>{{x.id}}</td>
<td>{{x.type_name}}</td>
<td>{{x.slug}}</td>
<td>{{x.created_date}}</td>
<td>{{x.update_date}}</td>
<td>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
Action
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li><a class="dropdown-item" href="#">Edit</a></li>
<li><a class="dropdown-item" href="#">Delete</a></li>
</ul>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% include 'common_alert.html' %}
</div>

{% endblock %}

Selanjutnya tambahkan librari berikut di settings.py


INSTALLED_APPS = [
----
'django.contrib.humanize',
---
]


F) Django Model Update


Buat class dengan nama AccountTypeEdit()

class AccountTypeEdit(TemplateView):
template_name = 'account/form.html'

@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def get_context_data(self, account_id, **kwargs):
context = super().get_context_data(**kwargs)
context['h_title'] = "Edit Data"
context['acc'] = AccountTypeModel.objects.get(id=account_id)
return context

Kemudian modifikasi form.html menjadi seperti berikut:

{% extends 'base.html' %}
{% block content %}
<h2>{{h_title}}</h2>
<div class="col-md-12 order-md-2 mb-4">
<form action="" method="post">
<input type="hidden" name="account_id" value="{{acc.id}}">
{% csrf_token %}
<div class="mb-3 mt-3">
<label for="account_type_name" class="form-label">Tipe Akun:</label>
<input type="text" class="form-control" id="account_type_name" placeholder="Tipe Akun" name="account_type_name" value="{{acc.type_name}}">
</div>
<button type="submit" class="btn btn-primary">SUBMIT</button>
</form>
</div>
{% endblock %}

Setelah itu modifikas tag html "edit", sehingga menjadi seperti berikut:


<li><a class="dropdown-item" href="/acc/account-type/edit/{{x.id}}">Edit</a></li>


Tambahkan method post kedalam class AccountTypeEdit()

def post(self, *args, **kwargs):
try:
account_id = self.request.POST.get('account_id')
typeName = self.request.POST.get('account_type_name')
acc = AccountTypeModel.objects.get(id=account_id)
acc.type_name = typeName
acc.save()

messages.success(self.request, "Data berhasil di update")
except Exception as e:
messages.error(self.request, str(e))

return HttpResponseRedirect("/acc/account-type")

F) Django Model Delete


Buat sebuah fungsi dengan nama accountTypeDelete()

@login_required   
def accountTypeDelete(request, account_id):
try:
AccountTypeModel.objects.filter(id=account_id).delete()
messages.success(request, "Data berhasil di hapus")

except Exception as e:
messages.error(request, str(e))

return HttpResponseRedirect("/acc/account-type")

Kemudian modifikasi tag "Delete"  menjadi seperti berikut:


<li><a class="dropdown-item" href="/acc/account-type/delete/{{x.id}}" onclick="return confirm('Are you sure you want to delete this item?');">Delete</a></li>


G) Konfigurasi URL


Buat sebuah file dengan nama urls.py di app account.

from django.urls import path
from account import views

urlpatterns = [
path('account-type', views.AccountType.as_view(), name='account_type'),
path('account-type/create', views.AccountTypeCreate.as_view(), name='account_type_create'),
path('account-type/edit/<int:account_id>', views.AccountTypeEdit.as_view(), name='account_type_edit'),
path('account-type/delete/<int:account_id>', views.accountTypeDelete, name='account_type_delete'),
]

H) Video Tutorial


Githubhttps://github.com/halovina/e-wallet/tree/django-model-crud

Baca artikel lainya:


  1. Mini Wallet Bagian 1 - Django Template dan Static File

  2. Mini Wallet Bagian 2 - Django Template Base HTML

  3. Mini Wallet Bagian 3 - Django Model dan Koneksi Database Mysql

  4. Mini Wallet Bagian 4 - Django User Register

  5. Mini Wallet Bagian 5 - Django Session Login

  6. Tutorial bassic Mysql bagian 1 - Create Read Update Delete

  7. Tutorial bassic Mysql bagian 2 - Inner, Left, Right, Cross Join

  8. Tutorial bassic Mysql bagian 3 - Filtering Data

  9. Tutorial bassic Mysql bagian 4 - Grouping Data 

  10. Tutorial bassic Mysql bagian 5 - Operator dan Clausa

  11. Tutorial bassic Mysql bagian 6 - Replace Statement

  12. Tutorial bassic Mysql bagian 7 - Constraint Data

  13. Tutorial bassic Mysql bagian 8 - Mengubah Struktur tabel

  14. Tutorial bassic Mysql bagian 9 - Subquery

  15. Tutorial bassic Mysql bagian 10 - Virtual Tabel

  16. Tutorial bassic Mysql bagian 11 - Control Flow Function

  17. Membuat service OTP bagian 1 - OTP dan PIN

  18. Membuat service OTP bagian 2 - Sequence Diagram

  19. Membuat service OTP bagian 3 - Model dan Serializer

  20. Membuat  service OTP bagian 4 - Validate OTP

  21. Membuat  service OTP bagian 5 - Api Client Service

  22. Membuat service user login bagian 1 - Konfigurasi Database

  23. Membuat service user login bagian 2 - Serializer dan JWT

  24. Membuat CRUD service product bagian 1 - Models Product

  25. Membuat CRUD service product bagian 2 - Function Serializer

  26. Membuat CRUD service product bagian 3 - Api Client Service

  27. Membaut CRUD service product bagian 4 - Auth User

  28. Membuat CRUD service product bagian 5 - TDR File Log

  29. Membuat CRUD service product bagian 6 - Unit Test

  30. Django upload file menggunakan FileSystemStorage