Django tutorial, part 4

김수민·2020년 5월 4일
0

Django+uWSGI+nginx

목록 보기
5/9

https://docs.djangoproject.com/ko/3.0/intro/tutorial04/

  • Form element 작성하기
  • 제너릭 뷰 사용하기

Form element 작성하기

<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 %}
    <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>
  • polls/urls.py 에 path()를 추가하는 작업은 part3에서 이미 했다.
// polls/views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Choice, 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,)))
  • vote() 뷰함수를 구현하였다.

** reverse() 함수가 특이하다. 이 함수는 뷰함수에 URL을 하드코딩하지 않도록 도와준다. redirect하기를 원하는 뷰의 이름을 URL패턴의 변수수분을 조합해서 해당 뷰를 가르키도록 하다.

  • vote()뷰함수를 성공적으로 마치고나면 투표결과를 보여주는 result() 뷰함수로 리다이렉트 된다.
// polls/views.py

from django.shortcuts import get_object_or_404, render

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

Generic View

  • 전달된 파라미터에 따라 DB에서 데이터를 가져오고 템플릿에 랜더링하는 일반적인 패턴을 위해 Django에서는 'Generic view' 시스템이라는 간단한 방식을 지원한다.

  • 제너릭 뷰는 위와 같은 일반적인 패턴을 추상화하여 Python 코드를 작성하지 않아도 된다.

    	1. URLconf를 수정
    1. 불필요한 view 삭제
    2. Django의 제너릭뷰 기반의 뷰 생성
  • URLconf 수정
    - urlpattenr 수정

  • views 수정
    - import django.views import generic

    • class DetailView(generic.DetailView):
profile
python developer

0개의 댓글