알쓸전컴(알아두면 쓸모있는 전자 컴퓨터)

django HttpResponseRedirect 하기 본문

Web /Django

django HttpResponseRedirect 하기

백곳 2017. 8. 14. 18:07

HttpResponseRedirect 


현재 App에서 다른 App 으로 이동을 해주는 url Redirect 을 해준다. 


이전 강의에서 이어 가도록 하겠습니다. 

polls/views.py

from django.shortcuts import get_object_or_404, render

# Create your views here.
from django.http import HttpResponseRedirect,HttpResponse
from .models import Question,Choice
from django.urls import reverse

def index(request):
    latest_question_list = Question.objects.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,)))


reverse의 polls:results' 는 

polls/urls.py

from django.conf.urls import url
from . import views

app_name = 'polls'

urlpatterns = [
    url(r'^$', views.index, name='index'),
    # ex: /polls/5/
    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
    # ex: /polls/5/results/
    url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
    # ex: /polls/5/vote/
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

에서 링크 됩니다. 

reverse('polls:results', args=(question.id,)) 의 결과는 

'/polls/3/results/'

가 됩니다. 


위의 polls/views.py >> def results 을 위해서 polls/templates/polls/results.html 을 만들어 줍니다. 

polls/templates/polls/results.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>

위와 같은 결과를 얻을수 있습니다. 




'Web > Django' 카테고리의 다른 글

DjangoTEST 하기  (0) 2017.08.15
제너릭 뷰 사용하기  (0) 2017.08.14
django 간단한 폼 만들기  (0) 2017.08.12
dajngo Template 에서 하드코딩된 URL 을 제거  (0) 2017.08.12
Template 시스템 사용하기  (0) 2017.08.12
Comments