6 වන ඒකකය: CRUD ක්රියාකාරකම්
අපි දැන් අපේ යෙදුමේ වැදගත්ම කොටසට ඇතුල් වෙනවා. ඒ තමයි පරිශීලකයාට දත්ත සමඟ වැඩ කරන්න ඉඩ දීම. ඕනෑම දත්ත-පදනම් වූ යෙදුමක මූලික ක්රියාකාරකම් 4 ක් ඇත. ඒවා කෙටියෙන් **CRUD** ලෙස හඳුන්වයි.
CRUD යනු කුමක්ද?
- Create - අලුත් contact එකක් ඇතුළත් කරන්න.
- Read - දැනටමත් ඇති contact ලැයිස්තුව බලන්න.
- Update - පවතින contact එකක නම හෝ අංකය වෙනස් කරන්න.
- Delete - අනවශ්ය contact එකක් මකා දමන්න.
පියවර 1: Read - සියලුම සටහන් බැලීම (List View)
අපි මුලින්ම database එකේ තියෙන සියලුම සටහන් එක පිටුවක ලැයිස්තුවක් විදිහට පෙන්වන්න හදමු. මේ සඳහා අපිට View එකක්, Template එකක් සහ URL එකක් අවශ්ය වෙනවා.
1a. View එක සෑදීම (`notes/views.py`)
Database එකෙන් සියලුම `Note` objects ටික අරගෙන, ඒවා template එකකට යවන function එකක් අපි `views.py` ගොනුවේ ලියමු.
# notes/views.py
from django.shortcuts import render
from .models import Note # අපේ Note model එක import කරගන්න
# ... අපේ home view එක මෙතන තියෙනවා ...
def notes_list(request):
notes = Note.objects.all() # 1. සියලුම Note objects ලබාගන්න
context = {
'notes': notes # 2. ඒවා 'notes' කියන නමින් dictionary එකකට දාන්න
}
return render(request, 'notes_list.html', context) # 3. context එක template එකට යවන්න
1b. Template එක සෑදීම (`notes_list.html`)
`templates` folder එක ඇතුළේ `notes_list.html` නමින් අලුත් file එකක් සාදා, view එකෙන් එවන `notes` ලැයිස්තුව පෙන්වන්න කේතය ලියමු.
<!-- notes/templates/notes_list.html -->
{% extends 'base.html' %}
{% block content %}
<h1 class="mb-4">මගේ සියලුම සටහන්</h1>
<div class="list-group">
{% for note in notes %}
<a href="#" class="list-group-item list-group-item-action">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">{{ note.title }}</h5>
<small>{{ note.created_at|date:"Y-m-d" }}</small>
</div>
<p class="mb-1">{{ note.content|truncatewords:20 }}</p>
</a>
{% empty %}
<p>ඔබ තවමත් කිසිදු සටහනක් ඇතුළත් කර නොමැත.</p>
{% endfor %}
</div>
{% endblock content %}
මෙහි `{% for note in notes %}` යනු Django Template Language (DTL) හි for loop එකකි. View එකෙන් එවන `notes` ලැයිස්තුවේ ඇති එකින් එක `note` object එක අරගෙන, එහි `title`, `created_at`, `content` වැනි දත්ත පෙන්වයි.
1c. URL එක සකස් කිරීම (`notes/urls.py`)
අවසාන වශයෙන්, `/notes/` යන ලිපිනයට කවුරුහරි ආවොත්, අපි දැන් සෑදූ `notes_list` view එක ක්රියාත්මක වෙන්න කියලා `urls.py` ගොනුවට කියන්න ඕන.
# notes/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('notes/', views.notes_list, name='notes-list'), # අලුත් URL එක
]
Server එක run කර, http://127.0.0.1:8000/notes/ වෙත ගිය විට, ඔබ ඇතුළත් කළ සටහන් ලැයිස්තුව දැකගත හැකිවේවි!