[Python] Django 투표 앱 만들기 (2)

2024. 12. 17. 22:33·Language/Python

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  (2) 2023.09.09
'Language/Python' 카테고리의 다른 글
  • [Python] Django 투표 앱 RESTful api로 리팩토링하기
  • [Python] Django Model, View 사용하기
  • [Python] Django 투표 앱 만들기 (1)
  • [Python] Django 프로젝트 생성하기
Doodo
Doodo
  • Doodo
    Doodo
    Doodo
  • 전체
    오늘
    어제
    • 분류 전체보기 (192)
      • CS (17)
        • Network (11)
        • Database (6)
      • Language (19)
        • Python (11)
        • SQL (6)
        • R (2)
      • Linux (17)
      • DevOps (35)
        • Git (7)
        • Docker (8)
        • Kubernetes (9)
        • GCP (4)
        • AWS (7)
      • Data Engineering (50)
        • 책 리뷰 (14)
        • Airflow (35)
        • Redis (1)
      • DBMS (21)
        • CUBRID (21)
      • ML & DL (2)
      • 코딩테스트 (24)
      • 프로젝트 (7)
        • 서울시 대기현황 데이터 적재 프로젝트 (4)
        • CryptoStream (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
Doodo
[Python] Django 투표 앱 만들기 (2)
상단으로

티스토리툴바