Published on

Basics of Django Part 2


Starting A Project


Models are simply where you describe the layout of your database. All model classes are inherited from django.db.models class, so make sure to add its import in the file in the project.

from django.db import models

# all the classes are inherited from models.Model
class Question(models.Model): # question will be the name of table
    pub_date=models.DateTimeField('date published')
    def __str__(self):
        return self.question_text

class Choice(models.Model):  # choice will be the name of the table
    def __str__(self):
        return self.choice_text

Our database will use question_text,pub_date,choice_text as column names and we will use these entities in our code as well.

 Note : Whenever we make changes to i.e. changes to databases; we have to make migrations.

Quick example This example model defines a Person, which has a first_name and last_name:

from django.db import models

class Person(models.Model):
	first_name = models.CharField(max_length=30)
	last_name = models.CharField(max_length=30)

first_name and last_name are fields of the model. Each field is specified as a class attribute, and each attribute maps to a database column. The above Person model would create a database table like this:

CREATE TABLE myapp_person (
	"id" serial NOT NULL PRIMARY KEY,
	"first_name" varchar(30) NOT NULL,
	"last_name" varchar(30) NOT NULL


$ python makemigrations
$ python migrate

When we enter these commands all the new tables in the database will be created.The migrate command will take care of our database but in case if we want to see what changes it makes at the SQL level, we can use this command : python sqlmigrate [app name] 0001

We can also use `python check` to check for any problems in our project without making any migrations or changes.

We can also use `python shell` to have a advance python-django shell where we can play with the APIs.

Django Admin Interface

To create a super user type python createsuperuser

from django.contrib import admin

# Register your models here.
from .models import Question

We we want to register any of our models in the admin interface we have to mention them in the file.

from django.contrib import admin
from .models import Question  # class Question
# Register your models here. # Question is the model name i.e. class name in 				   file


Django uses are module called URLconf to map all the urls.

Now the important thing to note is there is a `` file made by default in Django which points to our project's URL and there is also another `` that we create in our project that points to all the ``.

The file in the app directory contains all the views mapped to it.

from django.urls import path
from . import views
urlpatterns = [
	path('articles/<int:year>/', views.year_archive),
	path('articles/<int:year>/<int:month>/', views.month_archive),
	path('articles/<int:year>/<int:month>/<int:pk>/', views.article_detail),

The above code maps urls to [[#Views]] which are call back functions. The file in the project directory maps all the urls to the apps.include() is always used when mapping to a app , only admin site is the exception.

from django.contrib import admin
from django.urls import path,include

urlpatterns = [

path(route,view,kwargs,name) : where kwargs and name are optional parameters.


Views handle all the requests from the user. A certain view is shown to the type of request that user has made.To call a view we have to map it to a url.

# example code 
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse

def index(request):
    return HttpResponse("This is the index page")

A view does 3 basic things

  • Taking a request parameter.
  • Returning HTTPResponse object
  • Or raising an exception i.e. Http404

Creation of Project

  • Creating project django-admin start project [project name]
  • Run server python runserver
If server does not run due to the port already in use:
sudo lsof -t -i tcp:8000 | xargs kill -9 
  • Start app python startapp [app name]
  • Write [[#Views]]
  • Create a URLconf in the app directory with the name
  • Add the views in the url file.
  • Define [[#Models]]
  • Include app in the list of installed apps.
  • Make [[#Migrations]]
  • Add models to [[#Django Admin Interface]]