LoginSignup
1
0

More than 5 years have passed since last update.

Django チュートリアル: 地域図書館ウェブサイト (その6)

Posted at

こちらで作成したページの続きです。
Django チュートリアル: 地域図書館ウェブサイト (その5)

作者の Create,Update,Delete 機能をつけ加えます。

次のページの後半部分です。
Django Tutorial Part 9: Working with forms

Generic editing views からです。

1) catalog/views.py に次をつけ加えます。

catalog/views.py
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy

from catalog.models import Author

class AuthorCreate(CreateView):
    model = Author
    fields = '__all__'
    initial = {'date_of_death': '05/01/2018'}

class AuthorUpdate(UpdateView):
    model = Author
    fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']

class AuthorDelete(DeleteView):
    model = Author
    success_url = reverse_lazy('authors')

2) テンプレートの作成

catalog/templates/catalog/author_form.html
{% extends "catalog/base_generic.html" %}

{% block content %}
  <form action="" method="post">
    {% csrf_token %}
    <table>
    {{ form.as_table }}
    </table>
    <input type="submit" value="Submit">
  </form>
{% endblock %}
catalog/templates/catalog/author_confirm_delete.html
{% extends "catalog/base_generic.html" %}

{% block content %}

<h1>Delete Author</h1>

<p>Are you sure you want to delete the author: {{ author }}?</p>

<form action="" method="POST">
  {% csrf_token %}
  <input type="submit" value="Yes, delete.">
</form>

{% endblock %}

3) catalog/urls.py の最後へ追加

catalog/urls.py
省略
urlpatterns += [  
    path('author/create/', views.AuthorCreate.as_view(), name='author_create'),
    path('author/<int:pk>/update/', views.AuthorUpdate.as_view(), name='author_update'),
    path('author/<int:pk>/delete/', views.AuthorDelete.as_view(), name='author_delete'),

4) 開発サーバーを起動して、
http://127.0.0.1:8000/catalog/author/create にアクセス
create_mar1801.png

データを入れて、Submit
create_mar1802.png

create_mar1803.png

没年を修正する
http://127.0.0.1:8000/catalog/author/5 で詳細が表示されたら、
http://127.0.0.1:8000/catalog/author/5/update
にアクセスする。
update_mar1801.png

削除
http://127.0.0.1:8000/catalog/author/5/delete/ にアクセスする。
delete_mar1801.png

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