Overview
In this blog, we will see what Django is?
And also we’ll create one small project i.e Library website with a minimal amount of code and with a very easy explanation. The cause of this blog is to have a fundamental idea and concepts clear about the working process of Django.
So are you excited? I know you are then what we are waiting for? Let’s dive into Django.
Into the process
Before starting learning this great framework, please make sure that Python3 and the virtual environment library ( virtualenv ) is installed on your system.
First, create a directory named code on the system
Commands
$ cd ~/Desktop $ mkdir code && cd code
The next step is to install Django via virtualenv.
Bonus tip – It’s always a best practice to use a dedicated and newly created virtual environment for every fresh Python project you create.
$ virtualenv env $ source env/bin/activate
Virtual Environments and Packages¶
Once the environment is installed and activated, move with the further steps
(env)$ pip install django
All set, now we have Django installed in our system, let’s start with creating a new project.
A Django website includes a single project and more than one app within the project. Now, let’s create our all-new project of Django with the startproject commands.
Bonus tip – It’s better to include the period or dot . at the end (django-admin startproject project_name .) which installs the code in the current directory. By default, Django creates an additional directory, if we don’t add the period.
Commands
(env) $ django-admin startproject library_project
( library_project is the name of our project )
Start the local Django web server after running migrate to sync the database.
Commands
(env) $ python manage.py migrate (env) $ python manage.py runserver
All went well? If yes then open a web browser to http://127.0.0.1:8000/ to ensure that our project has been installed successfully.
The next step will be adding the apps. As we discussed previously, multiple apps can be supported by the Django project.
For a while, stop the local server now just by hitting control+c in the terminal and then create a books app.
Commands
(env) $ python manage.py startapp books
Let’s put together the files such that our Library project’s web page lists all of the books. Open the code editor of your choice (My personal favorite is VS Code and PyCharm) to the settings.py file. Now, The first thing we need to do is add the new app to our INSTALLED_APPS configuration. Keep sure that we need to add these newly created apps at the bottom as Django reads all of them in order, and the built-in core Django apps, such as auth and admin, to be initialized first.
# library_project/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Local 'books.apps.BooksConfig', # new ]
Now, run the python manage.py migrate command to sync our database.
Commands
(env) $ python manage.py migrate
Each web page created in Django requires a few files which includes a view, template and URL. But first, we’ll need to create a database model, so let’s get started.
Now, open the books/models.py in the code editor and update it as below.
Code :
# books/models.py from django.db import models class Book(models.Model): title = models.CharField(max_length=250) subtitle = models.CharField(max_length=250) author = models.CharField(max_length=100) isbn = models.CharField(max_length=13) def __str__(self): return self.title
This is a basic Django model. As you can see, there are four fields: title, subtitle, author, and ISBN. We also include a __str__ method. So, later in the admin panel, we can see the title of a book.
We created a new database model, So now we need to create a migration file to go along with it. We could just type one command – python manage.py makemigrations but if there are multiple apps with database modified, both would be added to the migrations file which will make debugging more challenging in the future. Keep migrations files as specific as possible. Then run migrate to update the database.
Commands
(env) $ python manage.py makemigrations books (env) $ python manage.py migrate
Now start entering data into our new model from the built-in Django app. But we must create a superuser account and update admin.py.
Start with the superuser account.
Commands
(env) $ python manage.py createsuperuser
Enter a username, email, and password. For security reasons, the text will not appear on the screen while entering your password.
Now update our book app’s admin.py file.
Code
# books/admin.py from django.contrib import admin from .models import Book
admin.site.register(Book)
That’s all we need! Startup the local server again.
Commands
(env) $ python manage.py runserver
Navigate to http://127.0.0.1:8000/admin and log in to it. After successful login, you will be redirected to the admin homepage.
Click on the link for Books. Then the “Add Book +” button is on the upper righthand corner.
You can type the title of a book here. We are redirected to the “Books” page after clicking the “Save” button, which lists all current books entries saved in our database.
We have data in our Django project now, but we need a way to expose it as a web page. This involves building views, URLs, and template files.
The views.py file defines how the content of the database model is displayed. Since we would like to list all books we will use the built-in generic class ListView.
Now, update the books/views.py file.
Code :
# books/views.py from django.views.generic import ListView from .models import Book class BookListView(ListView): model = Book template_name = 'book_list.html'
At first, we imported ListView and our Book model. Then we define a BookListView class that specifies which model and template to use (not created yet).
We are two more steps behind before we have a fully working web page. The first step is to make our template and the second one is to configure our URLs. Let’s start with the URLs.
Both the project-level urls.py file and the app-level urls.py file must be set up. When a user comes to our site, the first they’ll interact with is the urls.py file at the project-level. So, let’s configure that first.
Code :
# library_project/urls.py from django.contrib import admin from django.urls import path, include # new urlpatterns = [ path('admin/', admin.site.urls), path('', include('books.urls')), # new ]
We started by importing the built-in admin app, the path for our routes. When a user visits /admin/, they are redirected to the admin portal. For the books app route, we use the empty string “, which means that a visitor on the site will be redirected to the books app.
Now it’s time to configure our books/urls.py file. However, Django does not include a urls.py file by default in apps for some reason. As a result, we’ll have to make it ourselves.
Commands
(env) $ touch books/urls.py
(If you use Linux or macOS, otherwise create urls.py file in books folder)
Now within a code editor update the new file.
Code
# books/urls.py from django.urls import path from .views import BookListView urlpatterns = [ path('', BookListView.as_view(), name='home'), ]
So, here we import our views, configure BookListView with the empty string, and name it as a home (best practice).
Now, when a user goes to the homepage of our website they will first hit the project-level urls.py (library_project/urls.py) file, then will be redirected to app-level urls.py (books/urls.py) which specifies using the BookListView.
The final step is to create the template file for our home page. We have already specified its name in views.py, so, we simply create it with the same name.
Start by making a new templates folder within the books app, then create a books folder inside it and finally create a template file (book_list.html) inside it.
Commands
(env) $ mkdir books/templates (env) $ mkdir books/templates/books (env) $ touch books/templates/books/book_list.html
(touch command is working in Linux and macOS only. Windows users can create files manually.)
Now update the template file.
<!-- books/templates/books/book_list.html -->
<h1>All books</h1>
{% for book in object_list %}
<ul>
<li>Title: {{ book.title }}</li>
<li>Subtitle: {{ book.subtitle }}</li>
<li>Author: {{ book.author }}</li>
<li>ISBN: {{ book.isbn }}</li>
</ul>
{% endfor %}
Now, here we use the for tag to loop over. It means if we have 10 books in the database then this loop will run 10 times. Template tags must be included within opening and closing brackets and parentheses. So the format is {% for … %} and then we must close our loop later with {% endfor %}.
Now we can start up the local Django server and see our web page.
Commands
(library) $ python manage.py runserver
Navigate to the homepage which is at http://127.0.0.1:8000/
If we add more books, they will each appear here, too. This was a very quick run-through of a Django website.
Conclusion
This blog helps you to clear the basics of Django, on the other side django has many more functionalities which you can explore. We have built a basic application from scratch! By using the Django admin we can create, edit, or delete the content. In this blog, we used Django’s class-based views and a template to render it out. Hope you liked this blog!