trybeetle

take it slow!!

visual studioでpollsを作成


Posted on Jan. 31, 2018, 8:47 a.m.



今回は、visual studioの開発環境を使い、django tutorialにあるpollsアプリを作成します。

アプリケーション作成

projectを右クリック->Addを選択->Django appを選択(今回はアプリケーション名をpollsにしました。)

models作成

models.pyの記述は下記のとおりに


from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

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

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

makemigrations・migrateを実行

projectタブ -> Django Make Migrations

projectタブ -> Django Migrate

setting.py編集

INSTALLED_APPSに'polls'を追加


INSTALLED_APPS = [
    'app',
    # Add your apps here to enable them
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
]

MIDDLEWARE_CLASSを変更。django2.0へアップデートしたため、MIDDLEWAREに記述を変更。詳細はこちらのdocをチェック。


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

admin.pyの編集

QuestionとChoiceを追加する


from django.contrib import admin

from .models import Question, Choice

admin.site.register(Question)
admin.site.register(Choice)

views.pyの編集

下記のとおり


from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
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):
    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,)))

htmlの配置

templates/polls/配下に次の3ファイルを配置。

index.html


{% if latest_question_list %}
    
{% else %}
    

No polls are available.

{% endif %}

detail.html


{{ question.question_text }}

{% if error_message %}

{{ error_message }}

{% endif %}
{% csrf_token %} {% for choice in question.choice_set.all %}
{% endfor %}

results.html


{{ question.question_text }}

    {% for choice in question.choice_set.all %}
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
  • {% endfor %}
Vote again?

urls.pyの編集

まず、メインのurls.pyを編集


from django.urls import include, path
from django.contrib import admin
.....
urlpatterns = [
    ....
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

続いて、polls/urls.pyを編集


from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('/', views.DetailView.as_view(), name='detail'),
    path('/results/', views.ResultsView.as_view(), name='results'),
    path('/vote/', views.vote, name='vote'),
]
#

以上、でpollsアプリが完成しました。

起動確認です

serverを起動させます。
Projectタブ -> Start serverを選択

http://127.0.0.1:8000/admin/を開いて、管理画面からQuestionとChoiceを登録

http://127.0.0.1:8000/polls/を開いて起動確認

以上です


Category:django
Tag: django visual_studio
Jan. 31, 2018, 8:47 a.m.

Comments