Welcome to this video tutorial on building a Django application. Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. In this tutorial, we will guide you through the process of creating a simple Django application from scratch.
Prerequisites
Before you start, make sure you have the following prerequisites:
- Python installed on your system
- Django installed (
pip install django
) - A text editor or IDE of your choice
Step-by-Step Guide
1. Setting Up the Project
To create a new Django project, run the following command in your terminal:
django-admin startproject myproject
This will create a new directory named myproject
with all the necessary files and directories for a Django project.
2. Creating an App
Next, create a new app within your project by running:
cd myproject
python manage.py startapp myapp
This will create a new directory named myapp
with the basic files and directories for a Django app.
3. Defining Models
In your app directory, open the models.py
file and define your models. For example:
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
This defines a simple Product
model with a name
and price
field.
4. Creating Views
In your app directory, open the views.py
file and define your views. For example:
from django.shortcuts import render
from .models import Product
def product_list(request):
products = Product.objects.all()
return render(request, 'product_list.html', {'products': products})
This defines a view called product_list
that retrieves all products from the database and renders a template named product_list.html
.
5. Creating Templates
Create a new directory named templates
in your app directory. Inside this directory, create a new HTML file named product_list.html
. Add the following content to this file:
<!DOCTYPE html>
<html>
<head>
<title>Product List</title>
</head>
<body>
<h1>Product List</h1>
<ul>
{% for product in products %}
<li>{{ product.name }} - {{ product.price }}</li>
{% endfor %}
</ul>
</body>
</html>
This template displays a list of products with their names and prices.
6. Running the Development Server
To run the development server, navigate to your project directory and run:
python manage.py runserver
Open your web browser and go to http://127.0.0.1:8000/
. You should see the product list displayed.
Further Reading
For more information on building Django applications, check out the following resources: