오늘은 DjangoRestFramework(DRF)에 대해 알게 되었다.
강의를 들으면서 알게된 오류
from rest_framework.response import Response
from articles.models import Article
def index(request):
articles = Article.objects.all()
article = articles[0]
article_fr = {
'title': article.title,
'content': article.content,
'created_at': article.created_at,
'updated_at': article.updated_at,
}
return Response(article_fr)
Response를 이용했는데
이러한 오류가 떴다.
강의에서 나온 오류지만 내가 해결하고 싶어서 서치하고 시도해 봤다.
function download(){
$.ajax({
url: "/mdm/exam_app/get_assessment_count/",
dataType: 'json',
data:{
},
type:'GET',
success: function (data) {
alert("inside the success method");
},
error: function(){
console.log("error");
}
});
}
어떤사람도 나랑 같은 오류로 질문했다. 위와 같은 코드인데 이런 오류가 떴는데 뭐가 문제인지를 질문한 것 같다.
답변으로
If you're using a function based view, then this issue usually means you forgot to add the @api_view and the @renderer_classes decorator to your view.
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def get_assessment_count(request):
[...]
data = {'count': queryset.count()}
return Response(data, template_name='assessments.html')
... 음.. 일단 영어 문장을 해석해보니 @api_view와 @renderer_classes decorator을 추가해야 된다고 말하는 것 같다.
어디부터 어디까지 긁어와서 추가해야 하는지는 잘 몰라서 강의를 마저 재생시켰다.
from rest_framework.response import Response
from rest_framework.decorators import api_view
from articles.models import Article
# Create your views here.
@api_view(['GET'])
def index(request):
articles = Article.objects.all()
article = articles[0]
article_fr = {
'title': article.title,
'content': article.content,
'created_at': article.created_at,
'updated_at': article.updated_at,
}
return Response(article_fr)
맨 위
from rest_framework.decorators import api_view
를 추가하고
Response를 사용한 함수에
@api_view(['GET'])
를 추가해주면 끝!
나는 지금 GET만 사용해서 이렇게 표시된다.
@api_view(['GET', 'POST'])
이렇게 POST도 추가해서 사용하면
아래에 POST요청 가능한 창이 생긴다!
하나 하나 알아갈 수록 재미도 있지만 앞으로 먼 길이 남아 있어서 조금 막막하기도 하다.. 그래도 끝까지 가보자고!