- Set up a Virtual Environment (Optional)
python -m venv myenv source myenv/bin/activate # Or on Windows: myenv\Scripts\activate
- Install Django
pip install django
- Check Django Version
django-admin --version
Create a Django Project
django-admin startproject myproject
- Navigate to the Project Directory
cd myproject
- Run the Development Server
python manage.py runserver
- Create a Model Class: Define your data model in the models.py file.
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=50) publication_date = models.DateField() def __str__(self): return self.title
- Track Model Changes
python manage.py makemigrations
book = Book(title="Django for Beginners", author="William S. Vincent", publication_date="2023-01-01") book.save()
- Fetch all books from the database:
all_books = Book.objects.all()
- Filter books written by "William S. Vincent":
python_books = Book.objects.filter(author="William S. Vincent")
- Update data for a specific book (e.g., book with primary key 1):
book = Book.objects.get(pk=1) book.title = "Django for Professionals" book.save()
- Delete a specific book (e.g., book with primary key 1):
book = Book.objects.get(pk=1) book.delete()
- Create Python classes in the
models.pyfile to define database tables. - Each class field is mapped to a database column.
- Use the
migratecommand to create the database schema and store data.
from django.db import models class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() pub_date = models.DateTimeField('date published')
- Create Python functions or classes in the
views.pyfile to define the business logic of web pages. - Handle requests, fetch data from the model, and pass it to the template.
- Generate and return responses.
from django.shortcuts import render from .models import Post def post_list(request): posts = Post.objects.all() return render(request, 'blog/post_list.html', {'posts': posts})
- Create HTML template files in the
templatesdirectory. - Use Django template language to display data dynamically within the template.
- Render web pages dynamically using template tags and variables.
<!DOCTYPE html> <html> <head> <title>Post List</title> </head> <body> <h1>Blog Posts</h1> <ul> {% for post in posts %} <li>{{ post.title }}</li> {% endfor %} </ul> </body> </html>
- Define URL patterns in the urls.py file to route requests to view functions or classes.
- Map URL patterns using regular expressions.
- Django processes requests by calling the appropriate view based on the URL pattern.
from django.urls import path from . import views urlpatterns = [ path('posts/', views.post_list, name='post_list'), ]