Welcome to our SQLite with Django tutorial! This lesson will guide you through using SQLite as Django's default database and create a simple web application. Let's get started!
In this tutorial, we will explore how to use SQLite as the database for a Django project. Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. SQLite is a lightweight, file-based database that doesn't require a separate server.
pip install django)Before we dive into SQLite, let's create a new Django project:
django-admin startproject my_django_projectNavigate to the project directory:
cd my_django_projectNow, let's create a new app:
python manage.py startapp my_appBy default, Django uses SQLite3 as the database. To confirm, open the settings.py file in the my_django_project directory and look for the DATABASES section:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}Models in Django define the structure of the database tables. In our example, we will create a simple model for a Book:
# my_app/models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_year = models.IntegerField()After defining the model, we need to create the corresponding database table. Django accomplishes this using migrations:
python manage.py makemigrations my_app
python manage.py migrateA view in Django is responsible for rendering a template based on the data fetched from the database. Let's create a simple view to display our books:
# my_app/views.py
from django.shortcuts import render
from my_app.models import Book
def book_list(request):
books = Book.objects.all()
return render(request, 'book_list.html', {'books': books})Finally, let's create a template that will display our books:
<!-- my_app/templates/book_list.html -->
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Book List</title>
</head>
<body>
<h1>Book List</h1>
<ul>
{% for book in books %}
<li>{{ book.title }} by {{ book.author }} ({{ book.publication_year }})</li>
{% empty %}
<li>No books found.</li>
{% endfor %}
</ul>
</body>
</html>Now, when you run the server (python manage.py runserver), you should see your book list displayed in the browser. π
What is the default database engine used by Django?
That's it for this lesson! In the next tutorial, we'll learn about working with Django forms and CRUD operations. Stay tuned! π―