본문 바로가기
AI/데이터 엔지니어링 데브코스

[3주차-2] 장고를 활용한 API서버 만들기 - view 다루기

by aiant 2023. 4. 29.

view

polls/views.py에서

from .models import *
from django.shortcuts import render

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5] #날짜 순으로 최신 5개 질문 리스트
    context = {'first_question': latest_question_list[0]} #첫번째 질문 딕셔너리
    return render(request, 'polls/index.html', context) #render는 html파일을 그려주는 역할

polls/templates/polls/index.html에서

참고) html에서 변수를 인식하려면 {{변수}}꼴이어야 변수로 인식

<ul>
    <li>{{first question}}</li> 
<ul>

polls/templates/polls/index.html에서 조건문과 반복문 추가하기: {% %}

{% if questions %}
<ul>
    {% for question in questions %}
        <li>{{question}}</li>
    {% endfor %}
</ul>
{% else %}
<p>no questions</p>
{% endif %}

 

 

 

 

상세페이지 만들기

 

polls/views.py에서

def detail(request, question_id):
    question = Question.objects.get(pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

 

polls/urls.py에서

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('some_url', views.some_url),
    path('<int:question_id>/', views.detail, name='detail'),
]

 

polls/templates/polls/detail.html에서

<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %} #html에서는 set.all()이 아니라 set.all
    <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>

 

 

 

 

링크 클릭해서 상세페이지로 이동하기

polls/urls.py에서

from django.urls import path 
from . import views  

app_name = 'polls' #앱이름 정하기

urlpatterns = [     
    path('', views.index, name='index'),
    path('some_url', views.some_url), 
    path('<int:question_id>/', views.detail, name='detail'),     #디테일 이름 정하기
    
]

polls/templates/polls/index.html에서

{% if questions %}
<ul>
    {% for question in questions %}
         <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> #url 설정시 아까 정한 문자인 앱 이름(polls) : 디테일 이름(detail)로 설정
         
    {% endfor %}
<ul>
{% else %}
<p>no questions</p>
{% endif %}