get_object_or_404()
def detail(request, pk):
article = get_object_or_404(Article,pk=pk)
context = {
'article' : article,
}
Django View decorators
require_http_methods()
from django.views.decorators.http import require_http_methods
@require_http_method(['GET','POST'])
def my_view(request):
pass
require_POST()
from django.views.decorators.http import require_POST
@require_POST
def delete(request,PK):
#if로 확인하던것이 필요 없어짐
article = get_object_or_404(Article, pk=pk)
article.delete()
return redirect('aritlces:index')
# POST가 아닐때는 사용자가 405 error를 받음
만약 require_GET() 을 사용하고 싶다면 require_GET() 보다는 require_safe()를 사용하는것이 더 좋다.
Why?
Web servers should automatically strip the content of responses to HEAD requests while leaving the headers unchanged, so you may handle HEAD requests exactly like GET requests in your views. Since some software, such as link checkers, rely on HEAD requests, you might prefer using require_safe instead of require_GET.
https://docs.djangoproject.com/en/3.2/topics/http/decorators/