https://www.youtube.com/watch?v=oDNXcPJ0KCo&list=PLi4xPOplIq7d1vDdLBAvS5PmQR-p6KwUz&index=6
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
from django.urls import path
from . import views
urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
# ex: /polls/5/
path('<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
path('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
from django.http import HttpResponse
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5] #출판일자를 정렬하여 5개까지만 가져오고, 이 5개를 ,로 연결
output = ', '.join([q.question_text for q in latest_question_list]) # 나온 문자열을 response
return HttpResponse(output)
{% 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 %}
from django.http import HttpResponse
from django.template import loader
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
from django.shortcuts import render
from .models import Question
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)
from django.http import Http404
from django.shortcuts import render![](https://velog.velcdn.com/images/dhwhdcks/post/bc8b5d39-f884-4277-84f3-bdb874eb7b11/image.jpg)
from .models import Question
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
{{ question }}
from django.shortcuts import get_object_or_404, render
from .models import Question
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
template태그를 사용하여 url설정에 정의된 특정한 url 경로들의 의존성을 제거할 수 있습니다.
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
urls.py 파일에 app_name을 추가하여 어플리케이션의 이름공간 설정
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
https://www.youtube.com/watch?v=ZXxQQa-DWQs&list=PLi4xPOplIq7d1vDdLBAvS5PmQR-p6KwUz&index=7
<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>
input: 사용자가 무언가를 입력할 수 있도록 보여주는 태그
label: 이름을 보여주는 태그
path('<int:question_id>/vote/', views.vote, name='vote'),
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,)))
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})
<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>
ex: url에 전달된 변수에 따라 데이터를 가져오고, 템플릿을 로드하고 반환하는 경우가 흔하기 때문에
장고는 제네릭 뷰라고 불리는 단축키를 제공해준다.
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
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):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
이번 내용도 했던 내용이었지만 훨씬 더 어려운 느낌이었다.
내용나체만으로는 어려운 느낌보단 render() 나 제네릭 뷰처럼 처본 보는 내용들 때문에 조금 헷갈렸다. 그래서 render()와 제너릭 뷰에 대해 조금 더 알아보기로 했다.
과정
구글에 '장고 render()' 검색, 이후 아래 사이트에 들어가서 render와 redirect에 대한 내용 숙지
https://velog.io/@yoosk5485/render%EC%99%80redirect%EC%9D%98-%EC%B0%A8%EC%9D%B4
구글에 '장고 제네릭 뷰' 검색, 이후 아래 사이트에 들어가서 제네릭 뷰에 대한 내용 숙지
https://velog.io/@reowjd/Djangoview-%EC%82%B4%ED%8E%B4%EB%B3%B4%EA%B8%B0