A practical project – a Django web application
In the previous lessons we learned the basic parts of the Django framework:
- creating a project
- working with a database
- forms and user registration
Now we will put all of this together into one simple web application.
The project structure
Our project has the following structure:
project/
manage.py
blog/
models.py
views.py
urls.py
templates/
index.html
The model for articles
First we define the model in the file models.py.
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
text = models.TextField()
date = models.DateTimeField(auto_now_add=True)
This model stores articles in the database.
The view function
Then we create a function that displays the articles.
from django.shortcuts import render
from .models import Article
def index(request):
articles = Article.objects.all()
return render(request, "index.html",
{"articles": articles})
URL configuration
Now we connect a URL with the view function.
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index")
]
The HTML template
Finally we make the template templates/index.html.
<h1>List of articles</h1>
{% for article in articles %}
<h2>{{ article.title }}</h2>
<p>{{ article.text }}</p>
{% endfor %}
Adding articles
We can add articles through the Django admin panel.
http://127.0.0.1:8000/admin
The admin panel lets us manage all the data in the application.
Developing the application further
We can extend this project further:
- adding comments
- user profiles
- searching articles
- an API for mobile applications
Related tutorials
If you want to put your Django application on a real web server, see the following guides:
- Deploying a Django application to the Heroku platform (SR)
- How to deploy a Python application to Heroku (SR)
Frequently asked questions
What is a Django application?
A Django application is a part of a project that contains a feature of the web site.
Can one project have several applications?
Yes. A Django project often contains several applications.
How do I add data to the database?
Data can be added through the Django admin panel or through forms.
Can Django run large sites?
Yes. Django is used for large and scalable web applications.
