Python | Django | class-based viewsのCreateViewの使い方

2021年8月21日

公開日:2021/8/21

Pythonには,DjangoというWebアプリケーションフレームワークがある.フレームワークのため,Djangoを利用するとWebアプリを通常よりも短時間で開発することが可能になる.

class-based viewsは,viewsを実装する手段の1つであり,関数の代わりにPythonのオブジェクトとしてviewsを定義する.viewsの作成とデータの追加・更新・削除が容易になる.

前記事では,「class-based viewsのListViewの使い方」を作成した.前記事での設定をそのまま引き継いだ上で,本記事では,「class-based viewのCreateViewの使い方」を以下4つの構成にて記す.

  1. 基本の利用1
  2. 基本の利用2
  3. “insert_medicine"ページにおけるデフォルト値の挿入
  4. 参照

◆実施環境

Python 3.8.8
Django 3.2.3
VS Code 1.59.0

■class-based viewsのCreateViewの使い方

データを挿入する際にCreateViewが利用される.

  1. 基本の利用1

“ec_site/views.py"に追記し,以下のように編集する.

 from django.shortcuts import render
from django.views.generic.base import (
    View, TemplateView
)
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView # 追記箇所
from . import forms
import random
from .models import Medicines
from datetime import datetime
from django.urls import reverse_lazy # 追記箇所

class TopView(View):

    def get(self, request, *args, **kwargs):
        medicine_form = forms.MedicineForm()
        return render(request, 'top.html', context={
            'medicine_form': medicine_form,
        })

    def post(self, request, *args, **kwargs):
        medicine_form = forms.MedicineForm(request.POST or None)
        if medicine_form.is_valid():
            medicine_form.save()
        return render(request, 'top.html', context={
            'medicine_form': medicine_form,
        })

class HomeView(TemplateView):

    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['name'] = kwargs.get('name')
        context['alphabet'] = random.randint(0,9999)
        return context

class MedicineDetailView(DetailView):
    model = Medicines
    template_name = 'medicine.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['time'] = datetime.now()
        return context

class MedicineListView(ListView):
    model = Medicines
    template_name = 'medicine_list.html'

    def get_queryset(self):
        qs = super(MedicineListView, self).get_queryset()
        if 'name' in self.kwargs:
            qs = qs.filter(name__startswith=self.kwargs['name'])
        qs = qs.order_by('-price')
        return qs

class MedicineCreateView(CreateView): # 以下追記箇所
    model = Medicines
    fields = ['name', 'description', 'price']
    template_name = 'insert_medicine.html'
    success_url = reverse_lazy('ec_site:list_medicines')

    def form_valid(self, form):
        form.instance.create_time = datetime.now()
        form.instance.update_time = datetime.now()
        return super(MedicineCreateView, self).form_valid(form)

“ec_site/urls.py"に追記し,以下のように編集する.

from django.urls import path
from .views import ( # 変更箇所
    TopView, 
    HomeView, 
    MedicineDetailView,
    MedicineListView,
    MedicineCreateView,
    )

app_name = 'ec_site'

urlpatterns = [
    path('top/', TopView.as_view(), name='top'),
    path('home/', HomeView.as_view(), name='home'),
    path('detail_medicine/', MedicineDetailView.as_view(), name='detail_medicine'),
    path('list_medicines', MedicineListView.as_view(), name='list_medicines'),
    path('list_medicines/', MedicineListView.as_view(), name='list_medicines'),
    path('insert_medicine/', MedicineCreateView.as_view(), name='insert_medicine'), # 追記箇所
]

“ec_site/views.py"で"insert_medicine.html"を記載したので,"templates"フォルダに"insert_medicine.html"を以下のように作成する.

“templates/insert_medicine.html"を以下のように編集する.

<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <input type="submit" value="save">
</form>

VS Codeの"View"を開き,"Terminal"をクリックする.クリックするとVS Codeの下部にターミナルが開くので,”conda activate 仮想環境名”を実行し,仮想環境に移行する(移行方法の詳細はこちら).その後,ターミナルで"cd class_based_view"を入力し,ディレクトリを変更する.変更後,以下のように”python manage.py runserver”を実行する.以下が出力される.

(djangoenv) C:\Users\shiro\Desktop\210517_python development\myclassbasedviewtest\class_based_view
>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced). # 以下出力箇所
August 21, 2021 - 13:29:47
Django version 3.2.3, using settings 'class_based_view.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

上記の"http://127.0.0.1:8000/"をクリックすると,ブラウザが開き,以下画面が出力される.

ブラウザのURLに"http://127.0.0.1:8000/ec_site/insert_medicine"と入力すると以下"insert_medicine"ページに遷移する.

以下のように記述し,"Save"をクリックする.

成功すると,以下のように"list_medicines"のページに遷移する.

  1. 基本の利用2

項目1で作成した"ec_site/views.py"を以下のように編集する.

from django.shortcuts import render
from django.views.generic.base import (
    View, TemplateView
)
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView
from . import forms
import random
from .models import Medicines
from datetime import datetime
from django.urls import reverse_lazy

class TopView(View):

    def get(self, request, *args, **kwargs):
        medicine_form = forms.MedicineForm()
        return render(request, 'top.html', context={
            'medicine_form': medicine_form,
        })

    def post(self, request, *args, **kwargs):
        medicine_form = forms.MedicineForm(request.POST or None)
        if medicine_form.is_valid():
            medicine_form.save()
        return render(request, 'top.html', context={
            'medicine_form': medicine_form,
        })

class HomeView(TemplateView):

    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['name'] = kwargs.get('name')
        context['alphabet'] = random.randint(0,9999)
        return context

class MedicineDetailView(DetailView):
    model = Medicines
    template_name = 'medicine.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['time'] = datetime.now()
        return context

class MedicineListView(ListView):
    model = Medicines
    template_name = 'medicine_list.html'

    def get_queryset(self):
        qs = super(MedicineListView, self).get_queryset()
        if 'name' in self.kwargs:
            qs = qs.filter(name__startswith=self.kwargs['name'])
        qs = qs.order_by('-price')
        return qs

class MedicineCreateView(CreateView):
    model = Medicines
    fields = ['name', 'description', 'price']
    template_name = 'insert_medicine.html'
    # success_url = reverse_lazy('ec_site:list_medicines') # 削除箇所

    def form_valid(self, form):
        form.instance.create_time = datetime.now()
        form.instance.update_time = datetime.now()
        return super(MedicineCreateView, self).form_valid(form)

“ec_site/models.py"に追記し,以下のように編集する.

from django.db import models
from django.urls import reverse_lazy # 追記箇所

class BaseModel(models.Model):
    create_time = models.DateTimeField()
    update_time = models.DateTimeField()

    class Meta:
        abstract = True

class Medicines(BaseModel):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=500)
    price = models.IntegerField()

    class Meta:
        db_table = 'medicines'

    def get_absolute_url(self): # 以下追記箇所
        return reverse_lazy('ec_site:list_medicines')

上記を保存し,ブラウザのURLに"http://127.0.0.1:8000/ec_site/insert_medicine"と入力すると以下画面に遷移する.

以下のように内容を記述し,"Save"をクリックする.

内容に問題がなければ,"list_medicines"のページに遷移する.以下赤枠のように挿入したデータも確認できる.

  1. “insert_medicine"ページにおけるデフォルト値の挿入

“ec_site/views.py"に追記し,以下のように編集する.

from django.shortcuts import render
from django.views.generic.base import (
    View, TemplateView
)
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView
from . import forms
import random
from .models import Medicines
from datetime import datetime
from django.urls import reverse_lazy

class TopView(View):

    def get(self, request, *args, **kwargs):
        medicine_form = forms.MedicineForm()
        return render(request, 'top.html', context={
            'medicine_form': medicine_form,
        })

    def post(self, request, *args, **kwargs):
        medicine_form = forms.MedicineForm(request.POST or None)
        if medicine_form.is_valid():
            medicine_form.save()
        return render(request, 'top.html', context={
            'medicine_form': medicine_form,
        })

class HomeView(TemplateView):

    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['name'] = kwargs.get('name')
        context['alphabet'] = random.randint(0,9999)
        return context

class MedicineDetailView(DetailView):
    model = Medicines
    template_name = 'medicine.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['time'] = datetime.now()
        return context

class MedicineListView(ListView):
    model = Medicines
    template_name = 'medicine_list.html'

    def get_queryset(self):
        qs = super(MedicineListView, self).get_queryset()
        if 'name' in self.kwargs:
            qs = qs.filter(name__startswith=self.kwargs['name'])
        qs = qs.order_by('-price')
        return qs

class MedicineCreateView(CreateView):
    model = Medicines
    fields = ['name', 'description', 'price']
    template_name = 'insert_medicine.html'

    def form_valid(self, form):
        form.instance.create_time = datetime.now()
        form.instance.update_time = datetime.now()
        return super(MedicineCreateView, self).form_valid(form)

    def get_initial(self, **kwargs): # 以下追記箇所
        initial = super(MedicineCreateView, self).get_initial(**kwargs)
        initial['price'] = '1000'
        return initial

上記を保存し,ブラウザのURLに"http://127.0.0.1:8000/ec_site/insert_medicine"と入力すると以下画面に遷移する.Priceの項目にデフォルト値として"1000″が記載されている.

  1. 参照

https://docs.djangoproject.com/en/3.2/ref/class-based-views/generic-editing/#createview

以上