You are currently viewing Getting Started with Python and Django

Getting Started with Python and Django

  • Post author:
  • Post category:Python
  • Post comments:0 Comments
  • Post last modified:May 3, 2024

In this tutorial, we will walk through the process of setting up a basic Django project. Django is a high-level Python web framework that enables rapid development of secure and maintainable websites and web applications. By the end of this tutorial, you will have a working Django project with a simple web page.

Prerequisites

Make sure you have Python installed on your system. You can download it from Python’s official website.

To check if Python is installed, open a terminal or command prompt and type:

python --version

You should see a version number like Python 3.9.7. If Python is not installed, download and install it from the official website.

Step 1: Install Django

You can install Django using pip, Python’s package installer. Open your terminal or command prompt and run:

pip install django

This command will install the latest version of Django. After installation, verify it by checking the version:

django-admin --version

You should see a version number like 3.2.10.

Step 2: Create a Django Project

Now let’s create a new Django project. In your terminal, navigate to the directory where you want to create the project, then run:

django-admin startproject myproject

This command will create a new directory called myproject with the following structure:

myproject/
    manage.py
    myproject/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py
  • manage.py: A command-line utility that lets you interact with this Django project.
  • myproject/: The actual Python package for your project.
  • myproject/__init__.py: An empty file that tells Python that this directory should be considered a Python package.
  • myproject/settings.py: The settings/configuration for this Django project.
  • myproject/urls.py: The URL declarations for this Django project.
  • myproject/asgi.py: An entry-point for ASGI-compatible web servers to serve your project.
  • myproject/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project.

Navigate into the myproject directory:

cd myproject

Step 3: Create a Django App

A Django project is composed of one or more apps, which are web applications that do something. Let’s create a simple app called myapp. In the same terminal, run:

python manage.py startapp myapp

This will create a new directory myapp inside your myproject directory.

Step 4: Define Models

Models in Django are Python classes that represent database tables. Let’s define a simple model for our app. Open myapp/models.py and add the following code:

from django.db import models

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

    def __str__(self):
        return self.title

This Book model has three fields: title, author, and published_date. The __str__ method defines how an instance of the model will be displayed as a string.

Step 5: Make Migrations

After defining the models, we need to create database tables based on those models. Django provides migrations for this purpose. Run the following commands:

python manage.py makemigrations
python manage.py migrate

The makemigrations command creates migration files based on the changes you have made to your models. The migrate command applies those changes to the database.

Step 6: Create an Admin User

Django comes with a built-in admin interface that allows you to perform CRUD operations on your models. To use the admin interface, we need to create a superuser. Run the following command and follow the prompts:

python manage.py createsuperuser

Step 7: Register Models with the Admin

Next, let’s register our Book model with the admin interface. Open myapp/admin.py and add the following code:

from django.contrib import admin
from .models import Book

admin.site.register(Book)

Step 8: Create Views

Views in Django are Python functions or classes that take a web request and return a web response. Let’s create a simple view to display a list of books. Open myapp/views.py and add the following code:

from django.shortcuts import render
from .models import Book

def book_list(request):
    books = Book.objects.all()
    return render(request, 'myapp/book_list.html', {'books': books})

Step 9: Create Templates

Templates are HTML files that define the structure of your web pages. Let’s create a template to display the list of books. Create a new directory myapp/templates/myapp and inside it, create a file called book_list.html:

<!DOCTYPE html>
<html>
<head>
    <title>Book List</title>
</head>
<body>
    <h1>Book List</h1>
    <ul>
        {% for book in books %}
            <li>{{ book.title }} by {{ book.author }}, published on {{ book.published_date }}</li>
        {% endfor %}
    </ul>
</body>
</html>

Step 10: Create URLs

URLs in Django map URL patterns to views. Let’s create a URL pattern to display our list of books. Open myproject/urls.py and add the following code:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.book_list, name='book_list'),
]

Step 11: Run the Development Server

Now everything is set up. Let’s run the Django development server to see our project in action. In your terminal, make sure you are in the myproject directory and run:

python manage.py runserver

Visit http://localhost:8000 in your web browser, and you should see the “Book List” page displaying the books you added. You can also visit http://localhost:8000/admin to access the admin interface and add new books using the superuser account you created.

This is just the beginning of what Django can do. Explore the Django documentation to learn more about building powerful web applications with Django.

Leave a Reply