ruk·si

🍡 Django Tutorial
Create View

Updated at 2018-11-23 18:27

Add the following to polls/views.py with:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView

# ...

class PollCreateView(LoginRequiredMixin, CreateView):
    model = Question
    fields = ['text']

Edit polls/models/questions.py:

from django.urls import reverse

class Question(UUIDMixin, TimesMixin, models.Model):
    # ...

    def get_absolute_url(self):
        return reverse('polls:detail', kwargs={'pk': self.pk})

Edit polls/templates/polls/results.html:

# ...
<a href="{{ question.get_absolute_url }}">Vote again?</a>

Edit polls/templates/polls/index.html:

# ...
        <li>
            <a href="{{ question.get_absolute_url }}">{{ question.text }}</a>
        </li>
# ...

Edit polls/urls.py:

from django.urls import path

urlpatterns = [
    # ...
    path('create/', views.PollCreateView.as_view(), name='create'),
]

Create form template to polls/templates/polls/question_form.html:

<form method="post" novalidate>
    {% csrf_token %}
    <table>
        {{ form.as_table }}
    </table>
    <input type="submit" value="Save" />
</form>

How you can create questions if you are logged in:

# login
# http://localhost:8000/admin/
# create polls
# http://localhost:8000/polls/create/