5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[python] Djangoで今日のカレンダーを表示する

Last updated at Posted at 2022-12-17

環境

Django 3.1.13
Python 3.9.13

Code

Tree
├─core
│  ...省略
├─events (カレンダー表示目的で今回使用する)
│  ├─migrations
│  └─templates
└─myapp
│  ├─urls.py
│  ├─settings.py
│  ...省略
└─manage.py
myapp.urls.py
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),

    # このurl
    path('events/', include('events.urls'))
]
events.urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('<int:year>/<str:month>', views.home, name='home'),
]

/events/2020/June → year=2020, month=June
のような形でパラメータを受け取る

events.views.py
from django.shortcuts import render
import calendar
from calendar import HTMLCalendar
from datetime import datetime

def home(requests, year=datetime.now().year, month=datetime.now().strftime('%B')):
    # パラメータがない場合、今日の日付になるようにした。

    month_number = list(calendar.month_name).index(month)
    month_number = int(month_number)

    # カレンダー
    cal = HTMLCalendar().formatmonth(year, month_number)

    # 今日の日付を得る
    now = datetime.now()
    current_year = now.year
    current_month = now.month
    time = now.strftime('%I:%M %p')

    return render(requests, 'home.html',
                  {"year": year,
                   "month": month,
                   "month_number": month_number,
                   "cal": cal,
                   "current_year": current_year,
                   "current_month": current_month,
                   "time": time})
events.home.html
<div>
    <center>
        <br>
        {{cal |safe}}

        <br>
        Now:
        {{current_year}} / {{current_month}}
        {{time}}

    </center>
</div>

カレンダー表示

日付指定なし

image.png

日付を指定

image.png

おわりに

nodejs, flaskのようなマイクロフレームワークを触ってDjangoに触れると、ルールが多くて不便だと思っていたが、意外と便利さを感じる。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?