Welcome to the Django tutorial! Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. This guide will walk you through the basics of Django, from setting up your environment to building a simple web application.
Getting Started
Before you begin, make sure you have Python installed on your system. Django is written in Python, so you'll need to have Python 3.x installed.
Quick Installation
To install Django, you can use pip
, the Python package installer. Open your terminal or command prompt and run the following command:
pip install django
Your First Django Project
Once Django is installed, you can create your first project by running the following command:
django-admin startproject myproject
This will create a new directory called myproject
with a basic Django project structure.
Creating an App
Within your project directory, you can create a new app by running:
cd myproject
python manage.py startapp myapp
This will create a new app called myapp
within your project.
The Django Admin
The Django admin is a web interface for managing content in your Django project. To create an admin user, run:
python manage.py createsuperuser
Then, you can access the admin interface at /admin/
in your browser.
Templates
Django uses a templating language to create dynamic web pages. You can create templates in the templates
directory of your app.
Here's an example of a simple template:
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Welcome to my Django site!</h1>
</body>
</html>
Models
Django models are used to define the data structure of your application. You can create models in the models.py
file of your app.
Here's an example of a simple model:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
Views
Django views are functions that handle requests and return responses. You can create views in the views.py
file of your app.
Here's an example of a simple view:
from django.shortcuts import render
def home(request):
return render(request, 'home.html', {'title': 'Home Page'})
URLs
Django uses URLs to map requests to views. You can define URLs in the urls.py
file of your app.
Here's an example of a simple URL configuration:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
Run the Development Server
To run the development server, use the following command:
python manage.py runserver
Now, you can access your Django application at http://127.0.0.1:8000/
.
Further Reading
For more detailed information, check out the official Django documentation.