C:\projects\noori\polls\admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)
C:\projects\noori\polls\models.py
from django.db import models
from django.utils import timezone
from datetime import datetime
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
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
C:\projects\noori\polls\urls.py
from django.urls import path, include
from .views import *
app_name = 'polls'
urlpatterns = [
path('polls/', index, name="index"),
path('polls/<int:question_id>/', detail, name="detail"),
path('polls/<int:question_id>/results/', results, name="results"),
path('polls/<int:question_id>/vote/', vote, name="vote"),
]
C:\projects\noori\polls\views.py
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.template import loader
from .models import Question, Choice
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
'''
context = ', '.join([i.question_text for i in latest_question_list])
return HttpResponse(context)
'''
'''
template = loader.get_template("polls/index.html")
context ={"latest_question_list":latest_question_list}
return HttpResponse(template.render(context, request))
'''
context = {"latest_question_list": latest_question_list}
return render(request, 'polls/index.html', context)
def detail(request, question_id):
'''
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
context = {"question": question}
return render(request, 'polls/detail.html', context)
'''
question = get_object_or_404(Question, pk=question_id)
context = {"question": question}
return render(request, "polls/detail.html", context)
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,)))
C:\projects\noori\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>
-->
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
C:\projects\noori\templates\polls\index.html
C:\projects\noori\templates\polls\detail.html
<!--
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
{% if choice.vote %}
<li>{{ choice.choice_text }} - {{ choice.vote }}</li>
{% else %}
<li>{{ choice.choice_text }} </li>
{% endif %}
{% endfor %}
</ul>
-->
<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>
C:\projects\noori\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>
'Django' 카테고리의 다른 글
generic views (0) | 2023.05.06 |
---|---|
style 적용 (0) | 2023.05.04 |
Custom User Model(사용자 지정 User Model) (0) | 2023.05.03 |
Django 가상환경 구축 (0) | 2023.04.12 |
댓글