Welcome to the Django getting started guide. Django is a powerful Python web framework that enables developers to build robust web applications quickly and efficiently. In this tutorial, we will walk through creating your first web app using Django and SQLite, a lightweight database engine.

Prerequisites

  • Python installed (version 3.8 or higher)
  • Basic knowledge of Python programming
  • Command line familiarity
  • SQLite installed (optional, Django manages it internally)

Setting Up Your Environment

First, create a new directory for your project and navigate into it using your terminal or command prompt.

Run the following command to create a virtual environment:

python -m venv env

Activate the virtual environment:

On Windows:

.\env\Scripts\activate

On macOS/Linux:

source env/bin/activate

Installing Django

With your virtual environment activated, install Django using pip:

pip install django

Creating a New Django Project

Initialize a new Django project by running:

django-admin startproject myproject

Navigate into your project directory:

cd myproject

Starting the Development Server

Run the development server to verify everything is set up correctly:

python manage.py runserver

Open your browser and go to http://127.0.0.1:8000. You should see the default Django welcome page.

Creating a New App

Stop the server (Ctrl+C) and create a new app called blog:

python manage.py startapp blog

Registering the App

Open myproject/settings.py and add blog to the INSTALLED_APPS list:

INSTALLED_APPS = [ ... 'blog', ]

Creating a Basic Model

In blog/models.py, define a simple Post model:

from django.db import models class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True)

Applying Migrations

Create and apply migrations to update the database schema:

python manage.py makemigrations

python manage.py migrate

Creating an Admin User

To manage posts via the admin interface, create a superuser:

python manage.py createsuperuser

Follow the prompts to set username, email, and password.

Registering the Model with Admin

In blog/admin.py, register the Post model:

from django.contrib import admin from .models import Post admin.site.register(Post)

Running the Development Server

Start the server again:

python manage.py runserver

Visit http://127.0.0.1:8000/admin and log in with your superuser credentials. You can now add, edit, and delete blog posts through the admin interface.

Next Steps

From here, you can create views, templates, and URLs to display your blog posts to visitors. Django's powerful features make it easy to expand your web application.

Congratulations! You have successfully built your first Django web app with Python and SQLite.