An Introduction to Web Development with Django and Python

Table of Contents

  1. Overview
  2. Prerequisites
  3. Setup
  4. Creating a Django Project
  5. Creating a Django App
  6. Defining Models
  7. Creating Views
  8. Creating Templates
  9. Adding Static Files
  10. URL Mapping
  11. Testing the Application
  12. Conclusion

Overview

In this tutorial, we will learn how to develop web applications using Django, a powerful web framework written in Python. By the end of this tutorial, you will have a solid understanding of Django’s key concepts and be able to create your own web applications using Python.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python programming language. Familiarity with HTML and CSS will also be helpful, but not necessary.

Setup

Before we begin, make sure you have Python and Django installed on your machine. You can install Python from the official website (https://www.python.org) and Django using pip, the Python package manager: pip install django To verify that Django is installed correctly, run the following command in your terminal or command prompt: django-admin --version If you see the version number, you’re ready to proceed.

Creating a Django Project

The first step in creating a Django web application is to create a Django project. A project is a collection of settings, configurations, and applications for a specific website or web application.

To create a Django project, open your terminal or command prompt and navigate to the directory where you want to create your project. Once inside the desired directory, run the following command: django-admin startproject myproject Replace “myproject” with the name of your project. This command will create a new directory with the project structure.

Creating a Django App

Now that we have our project set up, let’s create a Django app. An app is a self-contained module that encapsulates a specific functionality of your web application.

To create a Django app, navigate to the root directory of your project using the terminal or command prompt and run the following command: python manage.py startapp myapp Replace “myapp” with the name of your app. This command will create a new directory with the app structure.

Defining Models

Models in Django are Python classes that represent database tables. They define the structure of the data and relationships between tables.

Inside the app directory, open the models.py file. This file is where you define your models. Let’s create a simple model for a blog post: ```python from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title
``` In this example, we define a `Post` model with three fields: `title`, `content`, and `pub_date`. The `title` field is a character field with a maximum length of 100 characters. The `content` field is a text field, and the `pub_date` field is a date and time field that automatically sets the current date and time when a new post is created.

Creating Views

Views in Django handle the logic behind the web pages. They interact with models to retrieve data and pass it to templates for rendering.

Inside the app directory, create a new file called views.py. In this file, let’s create a simple view to render a list of blog posts: ```python from django.shortcuts import render from .models import Post

def post_list(request):
    posts = Post.objects.all()
    return render(request, 'myapp/post_list.html', {'posts': posts})
``` In this example, we import the `render` function from `django.shortcuts` and the `Post` model from our app. The `post_list` function retrieves all the `Post` objects and passes them to the `post_list.html` template along with the `request` object.

Creating Templates

Templates in Django are HTML files that define the structure and layout of the web pages. They can include dynamic content using template tags and filters.

Inside the app directory, create a new directory called templates. Inside the templates directory, create another directory with the app’s name (myapp). Finally, inside the myapp directory, create a file called post_list.html: ```html

``` In this example, we use template tags and filters to iterate over the `posts` list and display the title, content, and publication date of each post.

Adding Static Files

Static files in Django are CSS, JavaScript, and image files that are served directly to the web browser. They are stored in the static directory.

Inside the app directory, create a new directory called static. Inside the static directory, create another directory with the app’s name (myapp). Finally, inside the myapp directory, add your CSS file (styles.css) and any other static files you need.

URL Mapping

URL mapping in Django determines which view function should be called for a specific URL pattern.

Inside the app directory, open the urls.py file. This file is where you define the URL patterns for your app. Let’s create a simple URL pattern to map the post_list view to the root URL: ```python from django.urls import path from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
]
``` In this example, we import the `path` function from `django.urls` and the `post_list` view from our `views.py` file. We then define a URL pattern that maps the root URL (`''`) to the `post_list` view.

Testing the Application

Now that we have everything set up, let’s test our application. In your terminal or command prompt, navigate to the root directory of your project and run the following command: python manage.py runserver This command starts the development server, and you should see output indicating that the server is running. Open your web browser and visit http://localhost:8000. You should see a list of blog posts rendered based on the data defined in the models.

Conclusion

Congratulations! You have learned the basics of web development with Django and Python. You should now have a good understanding of how to create a Django project, define models, create views, and render templates. You also know how to add static files and map URLs to views. Django provides numerous other features and functionalities that you can explore to enhance your web applications. Happy coding!