django의 작동 원리는 다음과 같다.
1) config/urls.py
-> include로 지정된 참조 위치로 이동
-> 또는 정의된 path 진행
# config/urls.py
from django.urls import path, include
# http://127.0.0.1:8000/blog/
path('blog/', include('blog.urls')),
2) 지정된 참조 위치 (blog/urls.py) 또는 Config/urls.py 에서 진행
* url이 가리키는 view의 함수를 실행하러 간다.
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
# http://127.0.0.1:8000/blog/
path("", views.index, name="index"),
]
-> 위의 코드로 실행하는 view 함수는 index가 된다.
3) view의 함수가 가리키는 html을 띄워준다.
: render 함수를 이용
: 값을 가져가도록 하려면 json 형식의 context 변수를 정의한 후 함께 보낸다.
from django.shortcuts import render
from .models import Question
def index(request):
# 함께 보낼 context 변수는 json 형식으로 지정
context = {
questions = Question.objects.all()
}
return render(request, "index.html", context)
4) index.html 구성
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Question_List</title>
</head>
<body>
<div>
{% for question in questions %}
<p>{{question.name}}</p>
<p>{{question.position}}</p>
<p>{{question.office}}</p>
<p>{{question.age}}</p>
<p>{{question.startedate}}</p>
<p>{{question.salary}}</p>
{% endfor %}
</div>
</body>
</html>
'IT > Django' 카테고리의 다른 글
[Django] #1 Django 웹페이지 만들기 사전작업 - Python 가상환경 설정, Django/ settings.py 수정, admin 생성 (0) | 2024.03.07 |
---|