/hello/urls.py
urlpatterns = [ path('', views.index, name='index'), path('create', views.create, name='create'), path('edit/<int:num>', views.edit, name='edit'), ]
/hello/templates/hello/create.html
<body class="container"> <h1 class="display-4 text-primary">{{title}}</h1> <table class="table"> <tr> <th>data</th> </tr> {% for item in data %} <tr> <td>{{item}}</td> <td><a href="{% url 'edit' item.id %}">Edit</a></td> </tr> {% endfor %} </table> </body>
– url ‘edit’ item.idで/edit/1というようにアクセスできるようになる
edit.htmlを作る
/hello/templates/hello/edit.html
<body class="container"> <h1 class="display-4 text-primary">{{title}}</h1> <form action="{% url 'edit' id %}" method="post"> {% csrf_token %} <table class="table"> {{ form.as_table }} <tr> <td></td> <td><input type="submit" value="click" class="btn btn-primary mt-2"></td> </tr> </table> </form> </body>
edit関数を作る
/hello/views.py
# edit def edit(request, num): obj = Friend.objects.get(id=num) if(request.method == 'POST'): friend = FriendForm(request.POST, instance=obj) friend.save() return redirect(to='/hello') params = { 'title': 'Hello', 'id': num, 'form': FriendForm(instance=obj), } return render(request, 'hello/edit.html', params)
引っ張る時は、’form’: FriendForm(instance=obj),として、updateの時はFriendForm(request.POST, instance=obj)とするのか。なお、createの時はobj = Friend()