패스트캠퍼스 캐시백 챌린지 18일차
지난 포스팅에 이어서 Django basic에 관한 포스팅을 하려고 해당 클립 복습 + 백엔드 개발 관련 클립을 수강하는식으로 챌린지를 진행하였다. 포스팅을 한방에 하고싶은데 양이 굉장히 많아보여서 다음1번의 포스팅까지 polls app에 대한 포스팅을 하게 될 것 같다. (polls app 포스팅해야하는것 까먹고 private repo에 push 해놓고 지웠었는데 다시 clone받아서 포스팅해주었다.)
백엔드 클립쪽은 Django rest framework에 관한 내용을 배우고있다. Insomnia같은 tool은 처음 사용해보고 있는데, postman과 굉장히 흡사하게 생겼지만 desktop에서 간편하게 사용할 수 있게 되어있다.
django rest api 문서를 같이 보면서 실습이 진행되었는데 해당 포스팅을 하게 될 때에는 어떤부분에서 막혔고 stackoverflow에서 찾아서 해결하였는지에 대한 경험들을 작성해보려고 한다.
Poll App 만들기(2)
Django의 admin페이지로 로그인하기 위해서는 다음과 같은 Command를 입력해야한다.
python manage.py createsuperuser
username, password 를 등록한뒤 python server를 열어주고, 로그인을 시도해본다.
python manage.py runserver
server 주소로 들어가고, 뒤에 /admin을 붙여 접속한다.
이는 django에서 기본적으로 제공해주는 것인데, 데이터를 제어할 수 있는 admin 페이지에 진입할 수 있다. 모든 회사가 개발자를 보유하고 있는 것은 아닐 것이기에 관리자 혹은 기획자가 이용하기 쉬운 형태로 되어있다.
admin.py에서 이처럼 모델을 import해서 추가해주면 사이트상에서 DB Table이 표기되게되고 , 삭제,변경,추가등의 동작을 할 수 있다.
polls/views.py에 뷰를 추가해준다.
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
polls/urls.py에 path를 추가해준다.
from django.urls import path
from . import views
urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
# ex: /polls/5/
path('<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
path('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
]
<int:question_id 의 의미는 >question_id 인자를 받아서 view의 함수로 넘겨준다는 의미이다.
Question을 몇개 뽑아서 콤마의 형태로 쭉 이어주어 표현해주는 동작은 다음과 같이 할 수 있다.
from django.http import HttpResponse
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
output = ', '.join([q.question_text for q in latest_question_list])
return HttpResponse(output)
# Leave the rest of the views (detail, results, vote) unchanged
html 파일을 리턴해주는 형식으로 만들기위해 polls에 templates 폴더를 만들어준다.
그리고 templates 내부에서 index.html을 생성해준다.
다음과 같은 진자언어를 index.html에 넣어준다.
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
latest_question_list가 있으면 아래의 for문이 돌게되어 ul tag가 반복적으로 만들어진다.
또한 if-end-endif 의 구조로 작성해주면 된다.
template을 활용하여 views.py를 수정해준다.
from django.http import HttpResponse
from django.template import loader
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
이때 인자의 값은 Json 형식으로 넘겨주게되는 것이다.
좀 더 간단하게 바꾸어주려면 render라는 함수를 사용하여준다.
polls/views.py를 다음과 같이 render를 사용하여 변경해준다.
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
이제 detail.html에 대한 내용을 만들어줄 것인데, polls/views.py의 detail 함수를 수정해준다.
def detail(request, question_id):
q = Question.objects.get(pk=question_id)
context = {'question' : q}
return render(request , 'polls/detail.html',context)
polls/detail.html은 다음과 같이 수정해준다.
{{ question }}
polls/[생성된 Question_id] 를 입력해주면 이제 그 Question에 대한 내용이 출력될 것이다.
404 에러를 띄워주기 위해서는 다음과 같이 수정해준다.
from django.shortcuts import get_object_or_404, render
from .models import Question
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
context = {'question' : q}
return render(request, 'polls/detail.html', {'question': question})
그렇다면 이제 detail.html에서 question에 관한 내용이 들어오면 그 question에 관련된 choice들이 li 태그로 묶여 출력되는 식으로 변경해보자.
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
for choice in question.choice_set.all 의 의미는 해당 question을 foreign key로 가지고 가지고 있는 choice들의 묶음이라고 볼 수 있다. 해당되는 내용들에 대해 li 태그로 반복적으로 생성해줄 것이다.
패스트캠퍼스 [직장인 실무교육]
프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.
fastcampus.co.kr
* 본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.