LoginSignup
3
4

More than 5 years have passed since last update.

Django2 公式チュートリアルのPollsアプリの機能追加【pollsの新規登録】

Posted at

公式チュートリアルにはない機能を追加

第一弾として、pollsをユーザが新たに登録する機能を解説します。

既存viewの編集

views.py
#下の3つを追加
from django.urls import reverse_lazy
from django.contrib import messages
from .forms import QuestionForm

中略
#CreateViewを追加
class CreateView(generic.CreateView):
    model = Question
    form_class = QuestionForm
    success_url = reverse_lazy('polls:index')

    def form_valid(self, form):
        result = super().form_valid(form)
        messages.success(
            self.request, '「{}」を新規作成しました'.format(form.instance))
        return result    

既存URLの編集

polls/urls.py
    path('create/', views.CreateView.as_view(), name='create'), #追加

forms.pyを新たに作成

polls/forms.py
from django import forms
from .models import Question

class QuestionForm(forms.ModelForm):
    """
    Question モデルの作成、更新用。
    """
    class Meta:
        model = Question
        fields = ['question_text', 'pub_date']

question_form.htmlを作成

question_form.html
<form method="post">
    {{ form }}
    <button>保存</button>
    {% csrf_token %}
</form>

index.htmlを編集

index.html
<hr>
<h3>Questionを新規追加</h3>
<a href="{% url 'polls:create' %}">新規作成</a>

以上でしっかりと動くと思います。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4