Templating sederhana menggunakan Django


Di Django urutan pyton membaca sebuah file berawal dari urls.py, lalu ke views.py dan selanjutnya ke template html.

Membuat Virtual Environment

Pertama-tama buka terminal dan buatlah sebuah directory atau folder dengan nama django lalu masuk ke directory tersebut

mkdir django
cd django

Buat sebuah Virtual Environment untuk project django yang akan kita buat dengan perintah

python -m venv Env

Berikutnya jalankan Virtual Environment yang sudah dibuat dengan perintah

Env\Script\activate.bat

Membuat Project

Setelah menjalankan Environment yang tadi sudah dibuat. Maka tahap selanjutnya membuat project django dengan nama mywebsite pada Environment tersebut dengan perintah:

django-admin startproject mywebsite

Perintah yang baru saja dijalankan akan menghasilkan file bernama manage.py dan directory mywebsite berserta isinya. Selanjutnya masuk ke directory mywebsite dengan perintah cd mywebsite lanjutkan membuat sebuah App dengan nama blog dan about menggunakan perintah

python manage.py startapp blog
python manage.py startapp about

Selanjutnya buat directory dengan nama templates untuk file HTML dan directory dengan nama static untuk menyimpan segala macam asset seperti img, javascript atau CSS dengan perintah

mkdir templates
mkdir static

Maka didalam directory mywebsite akan seperti gambar di bawah ini.

D:.
│   manage.py
│
├───about
│   │   admin.py
│   │   apps.py
│   │   models.py
│   │   tests.py
│   │   views.py
│   │   __init__.py
│   │
│   └───migrations
│           __init__.py
│
├───blog
│   │   admin.py
│   │   apps.py
│   │   models.py
│   │   tests.py
│   │   views.py
│   │   __init__.py
│   │
│   └───migrations
│           __init__.py
│
├───mywebsite
│   │   asgi.py
│   │   settings.py
│   │   urls.py
│   │   wsgi.py
│   │   __init__.py
│   │
│   └───__pycache__
│           settings.cpython-310.pyc
│           __init__.cpython-310.pyc
│
├───static
└───templates

Mengubah file Setting

Saat membuat sebuat App didalam project, maka App tersebut harus didefiniskan terlebih dahulu di file settings.py agar bisa dipakai. Maka tahap tahap selanjutnya adalah buka file mywebsite/settings.py ubah pada bagian TEMPLATES dan INSTALLED_APPS menjadi seperti ini

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Pada list DIRS di file settings.py ditambahkan templates karena nanti file HTML akan diletakan di directory yang bernama templates

Masih di file settings.py, lanjutkan untuk menambahkan baris ini dibawah list STATIC_URL

STATIC_URL = 'static/'

STATICFILES_DIR = [
    BASE_DIR / 'static'
]

STATICFILES_DIR untuk menentukan path directory static yang sudah dibuat diawal tadi untuk keperluan asset image dll.

Membuat file HTML

Buatlah file .html pada directory mywebsite/templates dengan code seperti berikut

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
</head>

<body>
    {% for link, name in nav %}
    <ul>
        <li><a href="{{ link }}">{{ name }}</a></li>
    </ul>
    {% endfor %}

    {{content}}
</body>

</html>

Views

Lalu modifikasi file blog/views.py menjadi seperti ini

from django.shortcuts import render

def index(request):
    context = {
        'title':'Blog',
        'content':'Ini adalah halaman blog',
        'nav':[
            ['/','Home'],
            ['/blog','Blog'],
            ['/about','About']
        ]
    }
    return render(request,'index.html',context)

Modifikasi juga file about/views.py menjadi seperti ini

from django.shortcuts import render

def index(request):
    context = {
        'title':'About',
        'content':'Ini adalah halaman About',
        'nav':[
            ['/','Home'],
            ['/blog','Blog'],
            ['/about','About'],
        ]
    }
    return render(request,'index.html',context)

Untuk file views di dalam mywebsite belum ada maka harus dibuat terlebih dahulu. Lalu isikan file mywebsite/views.py dengan kode berikut

from django.shortcuts import render

def index(request):
    context = {
        'title':'Home',
        'content':'Ini adalah halaman Home',
        'nav':[
            ['/','Home'],
            ['/blog','Blog'],
            ['/about','About'],
        ]
    }
    return render(request,'index.html',context)

URLS

Selanjutnya buat file urls.py pada directory blog dan isi filenya seperti ini

from django.urls import path

from . import views

urlpatterns = [
    path('',views.index)
]

Buat dan isikan file about/urls.py menjadi seperti ini

from django.urls import path

from . import views

urlpatterns = [
    path('',views.index)
]

Terakhir ubah urls.py pada directory mywebsite

from django.contrib import admin
from django.urls import path, include

from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('blog/',include('blog.urls'))
    path('about/',include('about.urls'))
]

Lalu jalankan project yang sudah dibuat dengan perintah

python manage.py runserver

Maka di terminal akan muncul seperti ini.

~ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
January 26, 2022 - 19:57:43
Django version 4.0.1, using settings 'mywebsite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

Buka browser lalu masukan url localhost:8000 maka tampilannya seperti ini

Leave a Reply

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