Laut BerceritaLaut Bercerita, novel terbaru Leila S. Chudori, bertutur tentang kisah keluarga yang kehilangan, sekumpulan sahabat yang merasakan kekosongan di dada, sekelompok orang yang gemar menyiksa dan lancar berkhianat. Buy |
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 // source of halovina
Dari gambar diatas ada sebuah table dengan nama account_type, table ini bisa kita sebut sebagai table master.
{% 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 %}
{% 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 %}
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
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')
context['acc'] = AccountTypeModel.objects.all().order_by('-id')
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',
---
]
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>
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")
@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>
from django.urls import path
from account import viewsurlpatterns = [
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'),
]
Github: https://github.com/halovina/e-wallet/tree/django-model-crud