설문조사 투표 애플리케이션 설계 - 장고 day2

POOHYA·2021년 12월 8일
0

Django

목록 보기
4/7
post-thumbnail

요구사항

설문에 해당하는 질문을 보여준 후 질문데 포함되어 있는 답변 항목에 투표하면 그 결과를 알려주는 예제

DB 설계

  • Question 테이블: 질문을 저장하는 테이블
  • Choice 테이블: 질문별로 선택용 답변 항목을 저장하는 테이블

화면 UI 설계

  • index.html : 최근에 실시하고 있는 질문의 리스트를 보여준다.
  • detail.html: 하나의 질문에 대해 투표할 수 있도록 답변 항목을 폼으로 보여준다.
  • results.html: 질문에 따른 투표 결과를 보여준다.

프로젝트 체계

프로젝트 생성 명령어

C:\dev\workspace\django1>django-admin startproject mysite

polls 애플리케이션 생성 명령어

C:\dev\workspace\django1>python manage.py startapp polls

프로젝트 설정 파일 변경

프로젝트에 필요한 설정값들은 settings.py 파일에 지정한다.

  • 26: DEBUG=True이면 개발 모드로, False이면 운영 모드로 인식한다.
  • 29: 운영 모드인 경우 ALLOWED_HOSTS에 반드시 서버의 IP나 도메인을 지정해야 하고, 개
    발 모두의 경우에는 값을 지정하지 않아도 ['localhost', '127.0.0.1']로 간주한다.
  • 41: polls 앱의 설정 클래스는 startapp polls 명령 시에 자동 생성된 apps.py 파일에
    PollsConfig라고 정의되어 있다. 그래서 장고가 설정 클래스를 찾을 수 있도록 모듈 경
    로까지 포함하여 'polls.apps.PollsConfig'라고 등록한다.
  • 78~83: 데이터베이스 설정 항목을 확인할 수 있다.
  • 111: 타임존 지정으로 최초에는 세계표준시(UTC)로 되어 있는데 한국 시간으로 변경한
    다.
#[ch3Lab/mysite/settings.py]
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-62d3uy3nhs3y3ao*gmc5@&2@i&o^a*q5r2w18nnw$&li4kg22m'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
   	 #추가
    'polls.apps.PollsConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Seoul'		#변경

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

기본 테이블 생성

migrate - 데이터베이스에 변경사항이 있을 때 이를 반영해주는 명령어

C:\dev\workspace\django1>python manage.py migrate

웹서버 실행 명령어

C:\dev\workspace\django1>python manage.py runserver

프로젝트 디렉토리의 모습을 보여주는 명령어

C:\dev\workspace\django1>tree /F ch3Lab

웹서버를 실행하고 localhost:8000에 접속하면 로켓이 보임
잘 만들었다

애플리케이션 개발하기 – Model

  • polls 애플리케이션에 Question과 choice 두 개의 테이블 정의
# [ch3Lab/polls/models.py]
from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text
  • Admin 사이트에 models.py파일에서 정의한 테이블도 보이도록 등록
# [ch3Lab/polls/admin.py]
from django.contrib import admin
from polls.models import Question, Choice

admin.site.register(Question)
admin.site.register(Choice)

애플리케이션 개발하기 – View 및 Template

  • 처리 흐름 설계

URLconf

  • URLconf를 코딩할 때 하나의 urls.py 파일에 작성할 수도 있고, 다음과 같이 mysite/urls.py와 polls/urls.py 2개의 파일에 작성할 수도 있다. 어떤 방식이 좋을까?
    두 번째가 좋은 방법이다. 즉, URLconf 모듈을 계층적으로 구성하는 것이 변경도 쉬워지고, 확장도 용이해지지 때문이다.
#[ch3Lab/mysite/urls.py]
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')),  # 추가

]
#[ch3Lab/polls/urls.py]
from django.urls import path
from polls import views

app_name = 'polls'

urlpatterns = [
    path('', views.index, name='index'),  # /polls/
    path('<int:question_id>/', views.detail, name='detail'),  # /polls/5/
    path('<int:question_id>/results/', views.results,
         name='results'),  # /polls/5/results/
    path('<int:question_id>/vote/', views.vote, name='vote'),  # /polls/5/vote/
]

뷰 함수 index() 및 템플릿 작성

  • 뷰 함수와 템플릿은 서로에게 영향을 미치기 때문에 보통 같이 작업하게 된다. 다만, UI 화
    면을 생각하면서 로직을 풀어나가는 것이 쉽기 때문에 뷰보다는 템플릿을 먼저 코딩하는 것
    을 추천한다.

  • 화면 UI 설계 - index.html

  • latest_question_list 객체는 index() 뷰 함수에서 넘겨주는 파라미터이다

<!--[ch3Lab/polls/templates/polls/index.html]-->
{% if latest_question_list %}
<ul>
    {% for question in latest_question_list %}
    <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
  • index() 함수 작성
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.urls import reverse
from polls.models import Choice, Question

#추가
def index(request):
    latest_question_list = Question.objects.all().order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

뷰 함수 detail() 및 폼 템플릿 작성

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.urls import reverse
from polls.models import Choice, Question


def index(request):
    latest_question_list = Question.objects.all().order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

#추가
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})
  • 화면 UI 설계 - detail.html
<!--[ch3Lab/polls/templates/polls/details.html]-->
<h1>{{ question.question_text }}</h1>

<!--에러가 없으면 스킵-->
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
    {% csrf_token %}
    {% for choice in question.choice_set.all %}
    <!--name은 파라미터이름-->
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
    {% endfor %}
    <input type="submit" value="Vote" />
</form>

뷰 함수 vote() 및 리다이렉션 작성

  • vote() 뷰 함수의 호출과 연계된 URL은 detail.html 템플릿 파일에서 받는다.
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.urls import reverse
from polls.models import Choice, Question


def index(request):
    latest_question_list = Question.objects.all().order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)
    
    
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})
    
#추가
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 += 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,)))

뷰 함수 results() 및 템플릿 작성

  • results() 뷰 함수의 호출과 연계된 URL은 votes() 뷰 함수의 리다이렉트 결과로 받는다.
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.urls import reverse
from polls.models import Choice, Question


def index(request):
    latest_question_list = Question.objects.all().order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)


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

#추가
def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})


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 += 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,)))

하 스프링으로 만들었던 우리 Otte사이트 장고로 다시 구축하려니 벌써 아득해진다

profile
김효주

0개의 댓글