[Django]CRUDのDelete

レコードのモデルインスタンスを取得してdeleteメソッドを実行する

urlspaternsの追記
/hello/urls.py

urlpatterns = [ 
	path('', views.index, name='index'),
	path('create', views.create, name='create'),
	path('edit/<int:num>', views.edit, name='edit'),
	path('delete/<int:num>', views.delete, name='delete'),
]

index.htmlの修正
/hello/templates/hello/index.html

{% for item in data %}
		<tr>
			<td>{{item}}</td>
			<td><a href="{% url 'edit' item.id %}">Edit</a></td>
			<td><a href="{% url 'delete' item.id %}">Delete</a></td>
		</tr>
	{% endfor %}

delete.htmlの作成
/hello/templates/hello/delete.html

<body class="container">
	<h1 class="display-4 text-primary">{{title}}</h1>
	<p>※以下のレコードを削除します。</p>
	<table class="table">
		<tr>
			<th>ID</th>
			<td>{{obj.id}}</td>
		</tr>
		<tr>
			<th>Name</th>
			<td>{{obj.name}}</td>
		</tr>
		<tr>
			<th>Gender</th>
			<td>
				{% if obj.gender == False %} male {% endif %}
				{% if obj.gender == True %} female {% endif %}
			</td>
		</tr>
		<tr>
			<th>Email</th>
			<td>{{obj.mail}}</td>
		</tr>
		<tr>
			<th>Age</th>
			<td>{{obj.age}}</td>
		</tr>
		<tr>
			<th>Birth</th>
			<td>{{obj.birthday}}</td>
		</tr>
		<form action="{% url 'delete' id %}" method="post">
		{% csrf_token %}
		<tr><th></th><td>
			<input type="submit" value="click" class="btn btn-primary">
		</td></tr>
	</form>
	</table>
</body>

delete関数を作る
/hello/views.py

def delete(request, num):
	friend = Friend.objects.get(id=num)
	if(request.method == 'POST'):
		friend.delete()
		return redirect(to='/hello')
	params = {
		'title': 'Hello',
		'id': num,
		'obj': friend,
	} 
	return render(request, 'hello/delete.html', params)

CRUDの基本は抑えました。