1
1

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.

カレンダーフォームの作成(Django)

Posted at

Django管理画面のカレンダーフォームを流用する

adminサイトには、以下のカレンダーフォームが実装されているため、この機能を流用する。
admin_calendar.png

  • 実装手順
    • 日付をDBに保存しない場合(forms.Form)
    • 日付をDBに保存する場合(models.Model)
    • テンプレートに表示する

日付をDBに保存しない場合(forms.Form)

  • AdminDateWidget()をwidgetに指定する(フォーム)
forms.py
from django import forms
from django.contrib.admin.widgets import AdminDateWidget
 
class DateForm(forms.Form):
    date_field = forms.DateField(widget=AdminDateWidget())

日付をDBに保存する場合(models.Model)

  • AdminDateWidget()をwidgetに指定する(フォーム)
models.py
from django.db import models
 
class DateModel(models.Model):
    date_field = models.DateField()
forms.py
from django import forms
from django.contrib.admin.widgets import AdminDateWidget
from .models import DateModel

class DateForm(forms.ModelForm):
    class Meta:
        model = DateModel
        fields = ('date_field',)
        widgets = {
            'date_field': AdminDateWidget(),
        }

テンプレートに表示する

  • スタイルシーとJavaScriptを追加
base.html
{% load static %}
<!doctype html>
<!-- <title>ユーザー登録・更新</title> -->
<!-- for admin widgets -->
    <!-- <link rel="stylesheet" type="text/css" href="{% static 'admin/css/base.css' %}"/> -->
    <link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}"/>
    <script type="text/javascript" src="{% url 'admin:jsi18n' %}"></script>
    {{ form.media }}
    <script type="text/javascript" src="{% static 'admin/js/core.js' %}"></script>
    <script type="text/javascript" src="{% static 'admin/js/admin/RelatedObjectLookups.js' %}"></script>

calendar_form.png

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?