1
0

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 5 years have passed since last update.

DjangoでTodoアプリを作成その2

1
Posted at

CreateView

データを新しく作るときに適したテンプレート

TodoCreateクラスを作成する。
fieldsで作成する入力フォームの要素を指定する。
success_urlはフォームをPOSTしたあとに表示するページを指定する。
reverse_lazyは表示するページを指定するための便利な関数。

views.py
from django.urls import reverse_lazy

class TodoCreate(CreateView):
    template_name = 'create.html'
    model = TodoModel
    fields = ('title', 'memo', 'priority', 'duedate')
    # リバースとは逆回し。
    success_url = reverse_lazy('list')

urls.pyにcreateを追加。name=を指定することで、reverse_lazy関数の引数に指定することができるようになる。

todo/urls.py
from .views import TodoList, TodoDetail, TodoCreate

urlpatterns = [
    path('list/', TodoList.as_view(), name='list'),
    path('detail/<int:pk>', TodoDetail.as_view(), name='detail'),
    path('create/', TodoCreate.as_view(), name='create'),
]

{% csrf_token %}はセキュリティ対策用。
form.as_pはpタグでフォームを作成するという意味。

create.html
{% extends 'base.html' %}

{% block content %}
    <form action="" method="POST">{% csrf_token %}
        {{ form.as_p}}
        <input type="submit" value="作成する">
    </form>

{% endblock content %}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?