Writing your first Fastview app
In this tutorial we’ll build on the official Django tutorial and walk you through building a fully-featured poll app which will consist of a public site where:
members of the public can view polls and vote in them
users can create and administrate their own polls
staff can administrate all polls
We will assume you’ve already followed the official tutorial, and have a basic understanding of class-based views.
If you want to skip ahead, the completed project is available on github as the Fastview example project.
Prepare your project
We’ll assume that you have just finished part 7 of the official tutorial, and have the
polls app in front of you. You have django
installed. You’ve also given all your
poll templates the base template templates/base_site.html
using a content
block.
We’re also going to change Question.was_published_recently
to use the past 30 days.
You can get a copy of this starting point from from https://github.com/radiac/django-tutorial-starter.
If you’d prefer to just read along we’ll cover everything as we go. We’re starting with these models:
import datetime
from django.contrib import admin
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published")
def __str__(self):
return self.question_text
@admin.display(boolean=True, ordering="pub_date", description="Published recently?")
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
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
Add some sample data
Going forward we’ll need some data. We want a good spread across years for when we get to filtering, so lets create some questions, one a week for 150 weeks - starting a year and a half ago, and running a year and a half into the future.
Either grab the management command from the Fastview example project, or run the
following code in ./manage.py shell
:
import datetime
from django.utils import timezone
from polls.models import Choice, Question
start = timezone.now() - datetime.timedelta(weeks=75)
for i in range(150):
question = Question.objects.create(
question_text=f"Question {i+1}", pub_date=start + datetime.timedelta(weeks=i)
)
Choice.objects.bulk_create(
[Choice(question=question, choice_text=f"Answer {j+1}") for j in range(5)]
)
Now we’re ready to make a start. Lets move on to part 1 of this tutorial to learn how to add Fastview to your project and set up your first view group.