오늘의 코드 [2022.10.26]
중요해서 반드시 기억할 필요가 있거나, 주의해야 할 코드를 답안 형식으로 주석(저의 코멘트)과 함께 정리해 보았습니다.
Q. 장고 거북이반 강의 복습
# user/views.py
def profile(request, username):
user = User.objects.get(username=username)
context = {
"user": user
}
return render(request, 'profile.html', context)
# profile.html 에서
<html>
...(생략)...
<body>
{{user}}
</body>
</html>
여기서 {{user}}는 context에서 지정한 “user”의 정보를 불러오는 것이다. (context는 옵션)
… (이후 내용 추가 예정)…
Q. Django Rest Framework 강의
# articles/admin.py
from django.contrib import admin
from articles.models import Article
admin.site.register(Article)
당연한 말이지만, admin에 다음과 같이 Article 모델을 등록해주는 것을 잊어버리면 안된다.
프로젝트파일/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'articles',
]
articles와 같은 설치한 앱 목록은 물론, rest_framework도 반드시 표시해야 한다.
articles/views.py
from rest_framework.response import Response
from rest_framework.decorators import api_view
from articles.models import Article
@api_view(['GET'])
def index(request):
articles = Article.objects.all()
article = articles[0]
article_data = {
'title': article.title,
'content': article.content,
'created_at': article.created_at,
'updated_at': article.updated_at,
}
return Response(article_data)
- 여기서 api_view는 아래 화면과 같이, 프론트 화면으로 볼 수 있도록 장고 Rest framework에서 제공해 주는 기능으로 볼 수 있다.
- 기존에 HttpResponse 를 사용했던 것과는 달리, Response를 사용하여 응답화면으로 보여줄 수 있다.
- Response에 article_data라고 호명한 딕셔너리를 변수로 사용할 수 있음. (다른 변수도 사용 가능)
- 처음에 IndexError: list index out of range <- 다음과 같은 에러가 발생했는데 입력된 데이터가 없어서 발생한 케이스로 admin으로 접속해서 article data를 임의로 입력하니 잘 나타났다. (위의 article = articles[0]의 ‘0’는 본인이 올린 게시물의 첫번째에 해당하는 index)

'스파르타코딩 AI웹개발 3기' 카테고리의 다른 글
| 내일배움캠프_TIL_2022.10.28 (0) | 2022.10.29 |
|---|---|
| 내일배움캠프_TIL_2022.10.27 (0) | 2022.10.28 |
| 내일배움캠프_TIL_2022.10.24 (0) | 2022.10.24 |
| 내일배움캠프_WIL_2022.10.23 (0) | 2022.10.23 |
| 내일배움캠프_TIL_2022.10.21 (0) | 2022.10.21 |