🚀
AppSeed Docs
  • AppSeed
  • Support
  • App Generator
  • Boilerplate Code
    • API Servers
      • API Unified Definition
      • API Server Django
      • API Server Flask
      • API Server Node JS
    • Boilerplate Django Dashboards
    • Boilerplate Django Apps
    • Boilerplate Flask Dashboards
    • Boilerplate Flask Apps
    • Boilerplate Jinja
    • Django Templates
      • Django Template Volt
      • Django Argon Dashboard
      • Django Material Dashboard
  • Developer Tools
    • Django API Generator
    • Django Dynamic API
    • Django Dynamic DataTables
    • Flask Dynamic API
    • Flask Dynamic DataTables
    • DB Introspection Tool
  • PRODUCTS
    • Full-stack
      • Full-Stack React Purity
      • Full-Stack React Material
      • Full-Stack React Datta Able
      • Full-Stack React Berry
    • React
      • React Node JS Berry
      • React Node JS Datta Able
      • React Node JS Datta PRO
      • React Node Material Kit PRO
      • React Firebase Datta Able
      • React Firebase Datta PRO
      • Django React Datta Able
      • Django React Datta PRO
      • Flask React Datta Able
    • Flask Apps
      • Flask Material Kit
      • Flask Material Kit PRO
      • Flask Material Kit 2 PRO
      • Flask Pixel Lite
      • Flask Pixel PRO
      • Flask Soft Design
      • Flask Soft Design PRO
    • Flask Dashboards
      • Flask Adminator
      • Flask AdminLTE
      • Flask Azia Dashboard
      • Flask Argon Dashboard
      • Flask Argon PRO
      • Flask Atlantis Dark
      • Flask Atlantis Dark PRO
      • Flask Black Dashboard
      • Flask Black PRO
      • Flask CoreUI
      • Flask Datta Able
      • Flask Datta Able PRO
      • Flask Datta Able ENH
      • Flask Gradient Able
      • Flask Light Bootstrap
      • Flask Light Blue
      • Flask Material Dashboard
      • Flask Material PRO
      • Flask MaterialPro Lite
      • Flask MaterialPRO
      • Flask Material Admin
      • Flask Star Admin
      • Flask Soft Dashboard
      • Flask Soft Dashboard Pro
      • Flask Shards Dashboard
      • Flask SB Admin
      • Flask Sleek Admin
      • Flask Volt
      • Flask Volt PRO
      • Flask Tabler
    • Django Apps
      • Django Pixel Lite
      • Django Pixel PRO
      • Django Material Kit
      • Django Material Kit PRO
      • Django Material Kit 2 PRO
      • Django Soft Design
      • Django Soft Design PRO
    • Django Dashboards
      • Django Adminator
      • Django AdminLTE
      • Django Azia Dashboard
      • Django Argon Dashboard
      • Django Argon PRO
      • Django Atlantis Dark
      • Django Atlantis Dark PRO
      • Django Black Dashboard
      • Django Black PRO
      • Django CoreUI
      • Django Datta Able
      • Django Datta Able PRO
      • Django Datta Able ENH
      • Django Gradient Able
      • Django Light Bootstrap
      • Django Light Blue
      • Django Material Dashboard
      • Django Material PRO
      • Django MaterialPro Lite
      • Django MaterialPro
      • Django Star Admin
      • Django Soft Dashboard
      • Django Soft Dashboard PRO
      • Django Soft Dashboard ENH
      • Django Shards Dashboard
      • Django SB Admin
      • Django Volt
      • Django Volt PRO
      • Django Tabler
    • Eleventy 11ty
      • Soft UI Design
    • Jinja Templates
      • Jinja Argon Dashboard
      • Jinja AdminLTE
      • Jinja Atlantis Lite
      • Jinja Black Dashboard
      • Jinja Datta Able PRO
      • Jinja Dashkit v3
      • Jinja Light Bootstrap
      • Jinja Material Dashboard
      • Jinja Now UI Dashboard
      • Jinja Paper Dashboard
      • Jinja Pixel Lite
      • Jinja Pixel PRO
      • Jinja SB Admin
      • Jinja Volt Bootstrap 5
      • Jinja Volt PRO
  • Features
    • Flask
      • Extended User Model
  • Free Samples
    • Django Samples
      • Django Create Model
      • Django User Profile
      • Django Sales Charts
      • Django Routing Sample
      • Django API Server
  • Technologies
    • Django
      • Getting Started
      • Django v4 Release
    • FastAPI
      • Getting Started
    • Flask
      • Getting Started
      • Flask v2.0 Release
    • MySql
      • Install MySql on Windows
      • Install MySql on Ubuntu
    • Material UI
      • Getting Started
    • Next JS
      • Getting Started
      • Sample Next.js Project
      • Deploy a Next.js application on Netlify
      • Best Practices for NextJS projects
    • Python
      • Getting Started
    • Supabase
      • Getting Started
  • Deployment
    • Google Cloud Platform
      • Deploy Django on GCP
    • App Platform by DO
      • App Platform - Deploy Django
    • AWS - Amazon Services
      • Deploy Django on AWS
    • Render Deployment Platform
      • Deploy Flask to Render
      • Deploy Django to Render
      • Deploy React to Render
      • Deploy Django & React to Render
  • Content
    • What IS
      • What IS Apache
      • What IS Bulma
      • What IS Boilerplate Code
      • What IS CentOS
      • What IS Django
      • What IS Eleventy
      • What IS Flask
      • What IS Gunicorn
      • What IS Heroku
      • What IS JAMStack
      • What IS Jinja
      • What IS Nginx
      • What IS Panini
      • What IS Pipenv
      • What IS Python
      • What IS React
      • What IS Static Site
      • What IS Svelte
      • What IS Ubuntu
      • What IS uWsgi
      • What IS WSGI
      • Two-Tier Architecture
      • Single-Tier Architecture
      • N-Tier Architecture
    • Getting Started
      • Getting Started with Django
      • Django Templates
      • Getting Started with Flask
      • Getting Started with Next JS
    • How To
      • OAUth - Get Github Secrets
      • OAUth - Get Twitter Secrets
      • Crawl Website in Python
      • Setup CentOS for coding
      • Setup Ubuntu for coding
      • Setup Windows for coding
      • Install Pyhton
      • Install Pyhton 3.8 on Ubuntu
      • Install WSL
      • Install Docker on Windows
      • Getting Started with Python
      • Django Customize Admin UI
      • Django Chart Example
      • Django - Add Debug Toolbar
      • Django MySql Database
      • Django Dockerizing App
      • Django Reset Password
      • Django Extend User Model
      • Django Integrate DRF Library
      • Django Data Tables
      • Django Simple Charts
      • Django Social Login
      • Django Stripe Payments
      • Django HEROKU Deployment
      • Django AWS Deployment
      • Django Google Cloud Deploy
      • Django Azure Deployment
      • Install Flask
      • Code a simple app In Flask
      • Structure a Flask project
      • Flask Dockerizing App
      • Flask Reset Password
      • Flask User Profile
      • Flask Integrate Flask-RestX
      • Flask Data Tables
      • Flask Simple Charts
      • Flask Social Login
      • Flask Stripe Payments
      • Flask Deploy on Apache
      • Flask Deploy on HEROKU
      • Flask AWS Deployment
      • Flask Google Cloud Deploy
      • Flask Azure Deployment
      • How to Implement JWT Authentication in React
    • Tutorials
      • Django - How to Install
      • Django For Beginners
      • Django Request Object
      • Django Forms
      • Django Auth System
      • Flask - Code a simple App
      • Minimal Programming Kit
      • Parse HTML Components
    • Programming Languages
      • Php
      • Python
    • Frameworks
      • Django
      • Flask
    • Design Systems
      • Argon Design System
      • Soft UI Design System
    • Partners
      • BootstrapDash Agency
      • Creative-Tim Agency
      • CodedThemes Agency
      • CoreUI Agency
      • Themesberg Agency
      • WrapPixel Agency
    • Bootstrap Templates
      • Adminator
      • AdminKit
      • AdminLTE
      • Azia Dashboard PRO
      • Atlantis Lite Template
      • Atlantis PRO Template
      • Argon Dashboard Template
      • Argon Dashboard PRO
      • Black Dashboard Template
      • Black Dashboard PRO
      • CoreUI Template
      • Datta Able Template
      • Datta Able PRO Template
      • Light Bootstrap Template
      • Light Bootstrap PRO
      • Material Dashboard Template
      • Material Dashboard PRO
      • Material UI Kit
      • MaterialPro Lite
      • MaterialPro Wpx
      • Now UI Dashboard
      • Now UI Dashboard PRO
      • Paper Dashboard
      • Paper Dashboard PRO
      • Pixel Lite Template
      • Pixel PRO
      • Star Admin Template
      • Soft UI Dashboard
      • Soft UI Dashboard PRO
      • Shards Dashboard
      • Volt Dashboard Template
      • Volt Dashboard Pro Template
      • Tabler Template
    • Bulma CSS Templates
      • Dashkit PRO
      • Dashkit PRO v3
    • React Templates
      • Berry React Dashboard
      • CoreUI React
    • Vue Templates
      • Vuetify Material Dashboard
    • How to Fix
      • Cannot import name 'TextField' from 'wtforms'
      • ImportError: cannot import name 'safe_str_cmp' from 'werkzeug.security'
Powered by GitBook
On this page
  • Install Python
  • Manage Dependencies
  • Install a Code Editor
  • Build a Django Project
  • Create New Application
  • Create New Model
  • Using Admin Section
  • Resources

Was this helpful?

  1. Content
  2. Tutorials

Django For Beginners

A comprehensive introduction to Django for beginners

PreviousDjango - How to InstallNextDjango Request Object

Last updated 3 years ago

Was this helpful?

This tutorial aims to help beginners getting started with Django, a popular Web Framework written in Python. To get maximum from this content, the audience should be familiar with a terminal and have a minimal set of tools already installed. , a modern code editor (, ), and versioning command-line tool should be enough to experiment with all the code.

Install Python

The core of dependency for Django is Python and we should install the interpreter first. Most of the systems come with Python already installed and we can easily check in the terminal:

$ python --version
Python 3.8.4       <-- All Good     

If the version displayed in the terminal is Python2, please note that this version for versioning and development since Jan.2020. To download and install Python access the , select the installer that matches the operating system, and follow the installation setup. Once the process is finished, recheck the Python version in the terminal.

Manage Dependencies

With Python up and running, we can install Django and other modules required by our development. The recommended way to install and manage the dependencies for a Python project is to use a virtual environment, a safe way to isolate the dependencies across multiple projects.

$ # Linux-based systems
$ virtualenv env
$ source env/bin/activate  

For Windows-based systems, the syntax is slightly different:

$ virtualenv env
$ .\env\Scripts\activate

Let's install Django, using PIP (official package manager for Python)

$ pip install django

The above command will install the latest stable version of Django. From this point, we can use all tools provided by Django to create a new project, apps and manage the project via Django CLI.

Install a Code Editor

Build a Django Project

A new project can be generated with ease in Django by using django-admin that provides a collection of settings for the database, Django, and security layer.

Create the project folder

$ mkdir my-django-project
$ cd my-django-project

Inside the directory, we will generate the core of our project using django-admin tool :

$ django-admin startproject config .

Note: Take into account that . at the end of the command.

Create the database and the app tables

$ python manage.py makemigrations
$ python manage.py migrate

Start the application

$ python manage.py runserver 
$
$ # Access the web app in browser: http://127.0.0.1:8000/

At this point we should see the default Django page in the browser:

Create New Application

In the previous section, we've generated the core of the project that handles the configuration and now we will create the first Django application to serve a simple page to the users.

$ python manage.py startapp app

Add a new route - edit app/views.py

from django.shortcuts import render
from django.http import HttpResponse     # <-- NEW

def hello(request):                      # <-- NEW    
    return HttpResponse("Hello Django")  # <-- NEW   

The next step is to inform Django that we've created a new app and update the routing to include the new definition.

Update the configuration to include the new app - core/settings.py

# File: config/settings.py (partial content)
...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app'                           # <-- NEW
]
...

Update the routing rules as below - core/urls.py

# File: config/urls.py (partial content)
...
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url   # <-- NEW
from app.views import hello                 # <-- NEW

urlpatterns = [
    path('admin/', admin.site.urls),
    url('', hello),                         # <-- NEW
]

After saving all changes we should no longer see the Django default page (the one with the green rocket):

Create New Model

Even simple applications require minimal storage for persistent data. Django provides out-of-the-box an SQLite database, just to help us start fast. During this section, we will create and interact with a new table (model).

Visualize the default SQL settings - config/settings.py

# File: config/settings.py (partial content)
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
... 

The ENGINE specify the technology used to manage the database. In our case is a lightweight (yet powerful) SQLite engine. NAME informs Django where to save the database on the filesystem.

Define a new model Books in sample application. The below changes should be added to sample/models.py:

# File: sample/models.py

from django.db import models                       

class Book(models.Model):                                 # <- NEW
    title            = models.CharField(max_length=100)   # <- NEW 
    author           = models.CharField(max_length=100)   # <- NEW
    publication_date = models.DateField()                 # <- NEW 

Tip - for a quick check over the latest changes we can run check subcommand.

$ python manage.py check
System check identified no issues (0 silenced).  

Generate the SQL code (migrate the database).

$ python manage.py makemigrations  # generate the SQL code
Migrations for 'sample':
  sample\migrations\0001_initial.py
    - Create model Book 

Apply changes on the database

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sample, sessions
Running migrations:
  Applying sample.0001_initial... OK 

Use the model via CLI

Once the model is created we can use it via the Django shell:

$ python manage.py shell
>>> 
>>> from sample.models import Book     # import the Book model in our context
>>> from django.utils import timezone  # used to provide the value for publication_date
>>>
>>> book1 = Book(title='The Adventures of Tom Sawyer', author='Mark Twain', publication_date=timezone.now() )
>>> book1.save()                       # save the new book

List all items (books) (using the CLI)

$ python manage.py shell
>>> 
>>> from sample.models import Book
>>> Book.objects.all()
<QuerySet [<Book: Book object (1)>]>

We can see our new book returned by the query. Let's improve the information that describes the object.

Django Model - add text representation of an object

To achieve this goal, we should define the __str__() method for the Book model

# File: sample/models.py

from django.db import models                       

class Book(models.Model): 
    title            = models.CharField(max_length=100) 
    author           = models.CharField(max_length=100)
    publication_date = models.DateField() 

    def __str__(self):       # <- NEW
        return self.title    # <- NEW

Let's restart the Django console and check the results:

$ python manage.py shell
>>> 
>>> from sample.models import Book
>>> Book.objects.all()
<QuerySet [<Book: The Adventures of Tom Sawyer>]>

Using Admin Section

Django comes by default with a usable admin dashboard that allows us to manage all app models and users with ease. In order to access the module, a superuser should be created using the Django CLI:

Create Django Superuser

$ python manage.py createsuperuser
sername (leave blank to use 'test'): admin
Email address: test@appseed.us
Password: ********
Password (again): ********
Superuser created successfully. 

CRUD (create, read, update, delete) actions are provided for all default models (users, groups) shipped by Django. To register the new models, Books in our case, we need just a few lines of code.

Register Book model to be visible in the admin section

# File: sample/admin.py

from django.contrib import admin

from .models import Book        # <- NEW

admin.site.register(Book)       # <- NEW 

After this small change in our code, we should see Books model listed in the admin page:

Django Admin - Edit Book Items

Resources

This section has plenty of options from the old-school (yet modern) to and . For those unfamiliar with any of these tools, VsCode might be a good choice to get started fast.

- official website

- download page

Thanks for reading! For more topics, feel free to Appseed.

Read more about (official docs)

Start fast a new project using development-ready

Python3
VsCode
Atom
GIT
has been discontinued
official page
Vim
VsCode
Atom
VSCode
VSCode
contact
Django
Django Starters
Programming Kit - VSCode editor.
Django - Default Project Page.
Django For Beginners - The first page.
Django Admin - Default View.
Django Admin - Register Books Model.
Django Admin - Edit Book Item.