Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the "batteries-included" philosophy and provides almost everything developers need right out of the box to build robust web applications. This tutorial will cover the basics of setting up a Django project, creating models, views, templates, and handling forms.
Before diving into Django, ensure you have Python installed on your system. You can download it from python.org. Additionally, install pip, the package installer for Python, if it's not already included with your Python installation.
First, you need to install Django using pip. Open your terminal or command prompt and run:
pip install django
Once Django is installed, create a new project by running the following command:
django-admin startproject mysite
This will create a directory named mysite with several files and directories. The most important ones are:
manage.py: A command-line utility that lets you interact with this Django project.mysite/: The actual Python package for your project. Its name defines the namespace for your project.
__init__.py: An empty file that tells Python this directory should be considered a Python package.settings.py: Settings/configuration for this Django project.urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site.asgi.py and wsgi.py: Entry-points for ASGI-compatible web servers and WSGI-compatible web servers to serve your project.Navigate into your project directory and run the development server:
cd mysite
python manage.py runserver
You should see output indicating that the server is running. Open a web browser and go to http://127.0.0.1:8000/ to see the default Django welcome page.
In Django, a project can contain multiple apps. Each app serves a specific function. Let's create a simple app called polls.
Run the following command to create a new app:
python manage.py startapp polls
This will create a directory named polls with several files and directories.
Models in Django are Python classes that define the structure of your database tables. Open polls/models.py and add the following code:
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
To manage your models through Django's admin interface, you need to register them. Open polls/admin.py and add:
from django.contrib import admin
from .models import Question, Choice
admin.site.register(Question)
admin.site.register(Choice)
Django uses a migration system to propagate changes you make to your models into the database schema. Run the following commands:
python manage.py makemigrations polls
python manage.py migrate
This will create the necessary tables in your database.
Views in Django are Python functions or classes that receive web requests and return web responses. Open polls/views.py and add:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
To map a URL to this view, you need to configure the URL dispatcher. Create a file named urls.py inside the polls directory and add:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
Then, include the polls URLs in the project's main urls.py file. Open mysite/urls.py and modify it as follows:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('polls/', include('polls.urls')),
]
Restart the development server if it's not already running. Visit http://127.0.0.1:8000/polls/ to see the "Hello, world. You're at the polls index." message.
Templates in Django are HTML files that define the structure of your web pages. Create a directory named templates inside the polls directory and then create another directory named polls inside it. This is to avoid naming conflicts with other apps.
Inside polls/templates/polls/, create a file named index.html and add:
<!DOCTYPE html>
<html>
<head>
<title>Polls Index</title>
</head>
<body>
<h1>Welcome to the Polls App!</h1>
</body>
</html>
Modify polls/views.py to use the template:
from django.shortcuts import render
def index(request):
return render(request, 'polls/index.html')
Restart the server and visit http://127.0.0.1:8000/polls/ again to see the new template.
Django provides a powerful form system that can handle user input and validate it. Create a file named forms.py inside the polls directory and add:
from django import forms
class QuestionForm(forms.Form):
question_text = forms.CharField(label='Question', max_length=200)
Modify polls/views.py to include a form view:
from django.shortcuts import render, redirect
from .forms import QuestionForm
def add_question(request):
if request.method == 'POST':
form = QuestionForm(request.POST)
if form.is_valid():
question_text = form.cleaned_data['question_text']
# Here you would save the question to the database
return redirect('index')
else:
form = QuestionForm()
return render(request, 'polls/add_question.html', {'form': form})
Create add_question.html inside polls/templates/polls/ and add:
<!DOCTYPE html>
<html>
<head>
<title>Add Question</title>
</head>
<body>
<h1>Add a New Question</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</body>
</html>
Modify polls/urls.py to include the new view:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('add/', views.add_question, name='add_question'),
]
Restart the server and visit http://127.0.0.1:8000/polls/add/ to see the form.
This tutorial covered the basics of setting up a Django project, creating models, views, templates, and handling forms. Django's robust framework provides a solid foundation for building complex web applications. As you continue learning, explore more advanced features like authentication, middleware, and custom management commands to enhance your projects.