# models.py
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse
from .models import Post
class PostDeleteView(DeleteView):
model = Post
def get_success_url(self):
return reverse('post_list')
def post(self, request, *args, **kwargs):
object = self.get_object()
if object.password != request.POST.get('password', ''):
messages.error(request, 'Wrong Password. Deletion Failed.')
return HttpResponseRedirect(
reverse('post_detail', args=[object.pk]))
messages.info(request, f'Successfully Deleted - {object.title}')
return super().post(self, request, *args, **kwargs)
template_name
기본값: <app_label>/<model_name>_confirm_delete.html
delete(request, *args, **kwargs)
함수가 호출될 때 모델에서 데이터가 삭제됨post(request, *args, **kwargs)
를 overridingpost()
를 overriding하고,
만약 Password Verification이 성공적으로 진행되었을 경우 super().post()
실행
get_object()
사용request.POST
로 직접 접근settings.py
의 INSTALLED_APPS
에 django.contrib.messages
추가 (이미 되어있음)<!DOCTYPE html>
<!-- board/templates/board/post_confirm_delete.html -->
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Delete {{ object.title }}</title>
</head>
<body>
<form method="post">
{% csrf_token %}
<p>Delete <b>{{ object.title|escape }}</b>?</p>
<input type="password" name="password" value="" required>
<input type="submit" name="confirm" value="Confirm">
</form>
</body>
</html>
<input>
의 required
필드는 제출할 때 해당 값이 비어있지 않는지 검증한다.{{ object }}
를 사용할 수 있다.