Django: building web applications in Python
Django is a popular web framework for building web applications in Python. In this post, we will explore the basics of Django and its key features.
Creating a Django project
To create a new Django project, we can use the django-admin
command-line utility:
django-admin startproject myproject
This will create a new Django project with the name myproject
.
Creating a Django app
In Django, an app is a self-contained module that contains models, views, and templates for a specific functionality of a web application. To create a new app in a Django project, we can use the manage.py
command-line utility:
python manage.py startapp myapp
This will create a new app with the name myapp
in the current Django project.
Defining models
In Django, a model is a Python class that represents a database table. Here is an example of defining a model for a blog post:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
pub_date = models.DateTimeField('date published')
In this example, we define a Post
model that has a title
, content
, and pub_date
field.
Creating views
In Django, a view is a Python function that takes a web request and returns a web response. Here is an example of defining a view that renders a template:
from django.shortcuts import render
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request, 'myapp/post_list.html', {'posts': posts})
In this example, we define a post_list
view that retrieves all the Post
objects and renders a template called post_list.html
.
Creating templates
In Django, a template is a text file that defines the structure and layout of a web page. Here is an example of a template for displaying a list of blog posts:
<html>
<head>
<title>My Blog</title>
</head>
<body>
{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<p>Published on {{ post.pub_date }}</p>
{% endfor %}
</body>
</html>
In this example, we define a template that displays a list of Post
objects.
Conclusion
In this article, we have explored the basics of Django and its key features. We learned how to create a Django project and app, define models, create views, and create templates. With these techniques, we can build powerful web applications in Python using Django.