Django is a powerful and popular Python web framework that provides a comprehensive toolkit for building web applications. Here's an introduction to web development using the Django framework:
1. What is Django?
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.
It follows the "batteries-included" philosophy, providing various tools and features for building web applications efficiently.
Getting Started with Django:
1. Installation:
Install Django using pip install Django.
2. Creating a Project:
Create a new Django project using the django-admin startproject projectname command.
3. Running the Development Server:
Navigate to the project directory and run the development server using python manage.py runserver.
Access the development server at http://127.0.0.1:8000/.
Django Components:
1. Models:
Define data models using Python classes.
Django automatically creates a database schema based on models.
2. Views:
Views handle HTTP requests and return responses.
Use views to interact with models and templates.
3. Templates:
Templates define the structure and layout of HTML pages.
Use template tags and filters to inject dynamic content.
4. URLs:
Define URL patterns in the urls.py file.
URL patterns map URLs to views.
5. Admin Panel:
Django provides a built-in admin panel for managing application data.
Register models to make them accessible through the admin interface.
6. Forms:
Create and process HTML forms using Django forms.
Validate and handle form data easily.
Example:
Here's a simple example to demonstrate the structure of a Django project and the creation of a basic web application:
1. Create a new Django project:
django-admin startproject myproject
2. Create a new Django app within the project:
cd myproject python manage.py startapp myapp
3. Define a model in myapp/models.py:
from django.db import models
class Item(models.Model): name = models.CharField(max_length=100) description = models.TextField()
Access the application at http://127.0.0.1:8000/ to see the list of items.
This example demonstrates a basic Django project structure, including models, views, templates, and URLs. Django's documentation offers more in-depth explanations of its features and capabilities, making it a versatile choice for building complex web applications.