BACK: Navigation

django-admin brings up a list of django-admin commands to use.

django-admin startproject mysite creates a new django project

python runserver runs the web app


If you go to, we are routed to a new place–the logic to handle this is in

Creating apps for our project:

We can have several apps in our project and copy paste apps into several different projects. We can create our first app with:

python startapp polls

We will now create a view. In polls/

from django.http import HttpResponse

def index(request):
    return HttpResponse("<h1>Hello, world. You're at the polls index.</h1>")

This creates the view, but in order to use it, we need to map it to a URL first. In polls/

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),

Now we have to map the URL of the app to a URL of the main project. In mysite/

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^polls/', include('polls.urls')),

This adds all the urls within polls/ If we add another view (ie url(r'^login$', views.login, name='login')) in polls/ and map that to polls/, we can visit that new view at

Connecting to Database, Looking at Settings

In mysite/, you can configure database settings down at DATABASES = { ... }

While here, take a look at INSTALLED_APPS. These are all the Django apps that are used in this Django instance. These apps usually make use of a database table, so we can use python migrate to create tables in our DB connection.

Now we can create our models–our DB schemas. In polls/

from django.db import models

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

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

The variable names will become column names in the DB. The Field type specifies what type of data will be stored in that column.

This little bit of information will create our DB for us and provide an API where we can use that information. We can add this into our mysite/ and then migrate again.

    'polls.apps.PollsConfig', # named from polls/

python makemigrations polls This tells Django that we’ve made some changes, seen in polls/migrations/ We can then call python sqlmigrate polls 0001 to run those changes and create SQL based on those changes. This doesn’t actually run the SQL–it’s just good to check what Django is about to do when you run python migrate again.


We can import these classes that we’ve made using:

from polls.models import Question, Choice

From here, we can directly interact with the database.

q = Question()
q.question_text= "What is your name?"

There are other API functionalities.