html 파일 생성
/polls 밑에 templates/polls/ 디렉터리 생성하고, 파일 추가

detail.html
{% include "./includes/header.html" %}
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
<legend><h1>{{ question.question_text }}</h1></legend>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
</fieldset>
<input type="submit" value="Vote">
</form>
{% include "./includes/footer.html" %}
index.html
{% include "./includes/header.html" %}
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
{% include "./includes/footer.html" %}
results.html
{% include "./includes/header.html" %}
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
{% include "./includes/footer.html" %}
includes/footer.html
</body>
</html>
includes/header.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'style.css' %}">
<title>투표 앱</title>
</head>
<body>
style.css 파일 생성
polls 디렉터리에 static 디렉터리 생성

style.css 파일 생성
body {
font-size: 17px;
line-height: 1.47059;
font-weight: 400;
letter-spacing: -.022em;
font-family: "SF Pro Text", "SF Pro Icons", "Helvetica Neue", "Helvetica", "Arial", sans-serif;
background-color: #fff;
color: #1d1d1f;
font-style: normal;
margin: auto;
max-width: 60vw;
}
polls/views.py 파일 수정
from django.db.models import F
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .models import Choice, Question
class IndexView(generic.ListView):
template_name = "polls/index.html"
context_object_name = "latest_question_list"
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.order_by("-pub_date")[:5]
class DetailView(generic.DetailView):
model = Question
template_name = "polls/detail.html"
class ResultsView(generic.DetailView):
model = Question
template_name = "polls/results.html"
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST["choice"])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(
request,
"polls/detail.html",
{
"question": question,
"error_message": "You didn't select a choice.",
},
)
else:
selected_choice.votes = F("votes") + 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))
polls/urls.py 파일 수정
from django.urls import path
from . import views
app_name = "polls"
urlpatterns = [
path("", views.IndexView.as_view(), name="index"),
path("<int:pk>/", views.DetailView.as_view(), name="detail"),
path("<int:pk>/results/", views.ResultsView.as_view(), name="results"),
path("<int:question_id>/vote/", views.vote, name="vote"),
]
mysite/settings.py 파일 수정
ALLOWED_HOSTS 다음과 같이 수정
ALLOWED_HOSTS = ['.localhost', '127.0.0.1', '[::1]']

테이블에 row 추가
DBeaver 접속해서 polls_question에 row 추가하기

마찬가지로 polls_choice에도 row 추가

결과 확인
서버 실행하고, localhost:8000/pulls에 접속
$ python manage.py runserver
localhost:8000/polls/

localhost:8000/polls/<int:pk>/

localhost:8000/polls/<int:pk>/results/

DB에도 요청이 정상적으로 반영됨

'Language > Python' 카테고리의 다른 글
[Python] Django 투표 앱 RESTful api로 리팩토링하기 (0) | 2024.12.17 |
---|---|
[Python] Django Model, View 사용하기 (0) | 2024.12.17 |
[Python] Django 투표 앱 만들기 (1) (1) | 2024.12.17 |
[Python] Django 프로젝트 생성하기 (1) | 2024.12.17 |
[Python] 네이버 카페 게시글 크롤링 selenium, bs4 (1) | 2023.09.09 |