django 예제 따라하기 (투표 앱 개발) 요약 Part 3,4
요약이라기 보다는 사이트에서 차례대로 읽으면서 작성하다보면 페이지가 완성된다.
실제로 구현된 소스를 올려 보겠다.
1,2장에서 프로젝트와 앱을 생성하면 기본적으로 파일들이 만들어지기 때문에
수정된 소스만 업로드 한다.
[mysite\mysite\settings.py]
polls만 추가
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
[mysite\mysite\urls.py]
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'mysite.views.home', name='home'),
#url(r'^blog/', include('blog.urls'),name='blog'),
url(r'^polls/', include('polls.urls',namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
)
[mysite\polls\admin.py]
from django.contrib import admin
from polls.models import Choice,Poll
# Register your models here.
class ChoiceInline(admin.TabularInline): #admin.StackedInline
model=Choice
extra=3
class PollAdmin(admin.ModelAdmin):
fieldsets=[
(None,{'fields':['question']}),
('Date information',{'fields':['pub_date'],'classes':['collapse']}),
]
inlines=[ChoiceInline]
list_display = ('question', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
search_fields = ['question']
admin.site.register(Poll,PollAdmin)
##admin.site.register(Choice)
실제로 구현된 소스를 올려 보겠다.
1,2장에서 프로젝트와 앱을 생성하면 기본적으로 파일들이 만들어지기 때문에
수정된 소스만 업로드 한다.
[mysite\mysite\settings.py]
polls만 추가
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
[mysite\mysite\urls.py]
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'mysite.views.home', name='home'),
#url(r'^blog/', include('blog.urls'),name='blog'),
url(r'^polls/', include('polls.urls',namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
)
[mysite\polls\admin.py]
from django.contrib import admin
from polls.models import Choice,Poll
# Register your models here.
class ChoiceInline(admin.TabularInline): #admin.StackedInline
model=Choice
extra=3
class PollAdmin(admin.ModelAdmin):
fieldsets=[
(None,{'fields':['question']}),
('Date information',{'fields':['pub_date'],'classes':['collapse']}),
]
inlines=[ChoiceInline]
list_display = ('question', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
search_fields = ['question']
admin.site.register(Poll,PollAdmin)
##admin.site.register(Choice)
[mysite\polls\models.py]
from django.db import models
import datetime
from django.utils import timezone
# Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
return self.pub_date>=timezone.now()-datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text
[mysite\polls\urls.py]
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
[mysite\polls\views.py]
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404,HttpResponseRedirect
from django.template import RequestContext, loader
from django.core.urlresolvers import reverse
from django.views import generic
from polls.models import Choice, Poll
# Create your views here.
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
def get_queryset(self):
"""Return the last five published polls."""
return Poll.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Poll
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Poll
template_name = 'polls/results.html'
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render(request, 'polls/detail.html', {
'poll': p,
'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=(p.id,)))
파이썬 코드는 여기서 끝
[mysite\polls\templates\polls\index.html]
{% if latest_poll_list %}[mysite\polls\templates\polls\detail.html]
<ul class="list-group">
{% for poll in latest_poll_list %}
<li class="list-group-item"><a href="{% url 'polls:detail' poll.id %}">{{ poll.question }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
<h1>{{ poll.question }}</h1>[mysite\polls\templates\polls\results.html]
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' poll.id %}" method="post">
{% csrf_token %}
{% for choice in poll.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>
<h1>{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
<a href="{% url 'polls:detail' poll.id %}">Vote again?</a>
댓글
댓글 쓰기