index.html - 질문의 목록을 보여주는 파일!
Django html에서 제공해 주는 특별한 표현법
1. 주석 - 단축키 : ctrl shift /
{% comment %}
Template 언어 차원에서 주석으로 간주
{% endcomment%}
{% comment %} {% endcomment%}
는 rendering engine에 대해 주석 처리되는 거예요.
html 주석 <!--주석--> 과 조금 다르죠??
Template 표현
{% %} django에선 template 태그는 이렇게 써요.
우리가 view.py의 q_list를 사용하면 html에서 키값 question_list을 써야 해요
q_list는 비어있는 list라 논리 값은 false예요.
if 문
Template 언어에서 if는
{% if %}는 {% endif %} 이렇게 표현돼요.
조건문
조건 문중 while은 조건, for는 숫자를 가지고 반복하기 때문에 우리는 for 문을 쓸 거예요.
{% %}에는 일반 프로그램의 for 문(변수 선언)과 같은 로직이 나와요.
우리가 값을 찍을 때는 중괄호를 두 개 중첩해야 해요. {{ }}
질문들에 대한 링크를 붙여줄 거예요.(<a> (Anchor Tag) 이용)
어떤 정보를 눌렀는지 알아야 그다음 페이지에서 그 주제에 맞는 항목을 보여주게끔 바뀌겠죠? 그래서 링크 안에 내가 어떤 정보를 눌렀어라는 정보를 넣어줄 거예요.
<li><a href="/polls/{{ question.id}}">{{ question.question_text }}</a></li>
<body>
{% if question_list %}
<ul>
{% for question in question_list %}
<li><a href="/polls/{{ question.id}}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<h1>현재 질문이 등록되어 있지 않아요! </h1>!
{% endif %}
</body>
admin page에서 table의 내용 확인 수정 삭제 가능 (django가 제공해 주는 기능) 이 있어요
질문 등록
+ Add question 클릭

/polls/id 예를 들어 /polls/3 3은 해당 질문의 아이디 값이에요.
mysite 폴더 urls.py
urls.py 에는 실행해야 하는 request가 들어 있어야 해요.
urls.py에 여러 request가 들어오고 여러 application 이 들어올 수도 있기 때문에
중첩 구조( include)로 나눠 활용해야 해요 - from django.urls import path, include
from django.contrib import admin
from django.urls import path, include
from polls import views ← 지워주세요
urlpatterns = [
path('admin/', admin.site.urls),
path('polls/', include('polls.urls'))
]
다음으로 polls 폴더에 urls라는 python 파일을 만들 거예요. urls.py
polls 폴더 urls.py
view 모듈을 import 해야 request를 받으니까 가져와요. 절대 경로는 나중에 문제가 생길 수 있어 상대 경로를 사용합니다.
애플리케이션 이름을 정해줍니다
add_name = 'polls'
계층 구조라 http://localhost:8000/polls/인식한 상태예요.
url configuration을 어떻게 표현하느냐??
<데이터 타입 : 변수> , name 에는 관계에 대한 적절한 이름을 붙여줘요.
from django.urls import path
from polls import views ← 조금전에 지웠던 것을 가져왔어요
add_name = 'polls'
urlpatterns = [
# http://localhost:8000/polls
path('', views.index, name='index'),
# http://localhost:8000/polls2
path('<int:question_id>/', views.detail, name='detail')
]
views. py
함수를 만들어 파라메타 변수로 urls.py의 question_id를 넣어줍니다.
question_id가 결국 Question Table에서 사용자가 선택한 질문의 PK입니다.
def detail(request,question_id):
get_object_or_404
get_object는 특정 pk(질문) table에서 해당 클래스의 인스턴스를 하나 뽑는 것
404의 의미는 찾을 수 없다는 뜻
하나를 뽑거나, 404 에러 표시(primary key에 있는 질문 객체를 뽑아 올 수 있어요)
키값으로 객체를 붙여줘요 {'question':question},
render다음은 무조건 request 나와요
이제 detail.html을 만들러 가봅시다.
polls 폴더 안에 templates 안에 polls에 html 파일을 생성해 주세요. detail.html
from django.shortcuts import render, get_object_or_404
from polls.models import Question
#현재 Database안에 있는 Question Table 속에 질문에 대한 목록을 가져오는 거예요
#이 목록을 가지고 결과 HTML을 Temlplate을 이용하여 만들어서 client에게 전달.
def index(request):
q_list = Question.objects.all().order_by('-pub_date') # DB 처리 포함한 로직 처리
context = {'question_list': q_list}
return render(request, 'polls/index.html', context)
def detail(request,question_id):
# question_id가 결국 Question Table에서 사용자가 선택한 질문의PK입니다.
question = get_object_or_404(Question, pk=question_id)
context = {'question':question}
return render(request, 'polls/detail.html', context)
polls 폴더 detail.html
http://localhost:8000/polls/ 의 질문에 대한 링크를 누르면 선택된 항목을 가지고 서버 쪽 프로그램을 호출할 수 있도록 사용자 입력 양식을 만들어 볼 거예요.(radio, button 등등)
안에는 데이터의 양이 많아질 수 있기 때문에 request 방식을 POST를 써요!
Django Template 상에서
{% csrf_token %}을 반드시 넣어주셔야 해요.
현재 Question instance를 가지고 있는데 이와 연관된 Choice 객체를 가져와서 화면에 출력해야 해요.
{% question.choice_set.all %} 객체와 연결된 choice table의 집합을 지칭해요.
이제 radio button을 표현할 거예요.
type과 name은 똑같이 맞춰주고 id 랑 value 값만 다르게 for 문에 넣어주세요!
input type="submit" 은
<head>
<meta charset="UTF-8">
<title>Title</title>
<h1>{{ question.question_text }}</h1>
<form action="http://localhost:8000/polls/"
method="POST">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="myChoice"
id="choice{{ forloop.counter }}" value="{{choice.id}}}">
<label for="choice{{ forloop.counter }}">
{{choice.choice_text}}
</label>
<br>
{% endfor%}
<input type="submit" value="Votes!!!">
</form>
</head>
<body>
</body>
admin page 이동!!
http://localhost:8000/admin/
질문에 연결된 항목들을 추가

http://localhost:8000/polls/ 에서 확인


'Back end' 카테고리의 다른 글
| 0728 Django 게시판만들기 (0) | 2021.07.28 |
|---|---|
| 0723 Django project3 (0) | 2021.07.23 |
| 0721 Pycharm 설정 (0) | 2021.07.21 |
| 0720 Django 프로젝트 만들기 (0) | 2021.07.20 |
| 0720 Django (0) | 2021.07.20 |
댓글