Django templates

◾️usage of template

  1. create templates directory and configure settings
TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            os.path.join(BASE_DIR, "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",
            ],
        },
    },
]

2. set urls for routing and create template html file

ex) xxx.xxx.xxx.xxx

  • configure core routing
urlpatterns = [
    path("", include("core.urls", namespace="core")),
    path("admin/", admin.site.urls),
]
  • create core/urls.py and route it to rooms.views
from django.contrib import admin
from django.urls import path, include
from rooms import views as room_views


app_name = "core"

urlpatterns = [
    path("", room_views.all_rooms, name="home"),
]
  • rooms.views render template html(rooms/home.html)
from datetime import datetime
from django.shortcuts import render
from django.http import HttpResponse
from . import models


# Create your views here.
def all_rooms(request):
    all_rooms = models.Room.objects.all()
    return render(request, "rooms/home.html", context={"rooms": all_rooms})

{% extends "base.html" %}

{% block page_name %}
    Room | airbnb
{% endblock page_name %}

{% block content %}
    {% for room in rooms %}
        <h2>{{room.name}} | ¥{{room.price}}</h2>
    {% endfor %}
{% endblock %}

◾️ home.html extends base.html

<!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>{% block page_name %}{% endblock page_name %}</title>
</head>
<body>
    {% include "partials/header.html" %}

    {% block content %}{% endblock content %}

    {% include "partials/footer.html" %}  
</body>
</html>

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です