The world of web applications, services, and software was somewhat dull and reserved for the elite developers until the famed Django Framework showed up. Django is what we can describe as the jack of all trades in the web design and development world. Whether you are after an API, web app, web service, etc., you won’t regret the consideration of going with this resourceful framework.
It is a free and open-source Python-based web framework that strictly complies with the architectural pattern of model-template-views. Under the Django software foundation, experienced developers are responsible for its creation and maintenance. Django ensures that its users do not have to re-invent the wheel by focusing on writing apps.
The thing about Django is that it is relatively easy once you have everything set up on your machine to only concentrate on writing code. There is a thin line between studying Django and studying Python, which is why this tutorial article has surfaced. We want to keep you from concentrating more on your Django project structure and divert your attention to learning more about the Python project or app you are developing.
Consider this scenario, every time you are on the internet pursuing a solution that can take your Django project closer to completion. You will find a variety of workarounds offered to fix a bug you are familiar with or extend your Django project’s functionality. Moreover, maybe you are not working on a Django project yet, but you feel like the solution or concept that has crossed your path will be useful shortly when you finally give in to the coding spell.
Testing such concepts or solutions requires a functional Django project skeleton because the website or blog site that offers it might not give you a complete set up of the Django project for you to execute it effectively. Therefore, the concept of not re-inventing the wheel under the Django framework does not apply to such circumstances that only require you to test a few lines of code.
Think of the Django project set up as a book or diary. Every time you need to document something important, you only need to open a page and write. You do not need to create a book and its pages before documenting something useful. This tutorial article gives you an alternative to avoid working with a single book’s page when you can auto-populate the other blank pages for you to test the newly found concept or solution that might be an interesting addition to your current or future Django project.
Django Project Prerequisites and Configurations
To kick off this article adventure, we have to look at what your machine needs before it can fully embrace a Django project’s execution under its development environment.
It is a no brainer that since Django is Python-based, we must support its endeavor to install the right or compatible Python version. Since we are currently embracing Python 3.x for reasons of superiority over Python 2.7, it is recommended that you either work with Python 3.6 or 3.8.
You can check the current Python version on your Linux system through the following terminal command.
$ python3 -V
If your Linux OS is Ubuntu 16.10 or similar, it is recommended you work with Python 3.6. You can install it through the following commands.
$ sudo apt update $ sudo apt install python3.6
On the other hand, you might be using a Linus OS version like the latest Ubuntu 20.10 LTS (Long Term Support). Such an OS requires a more recent Python version. You can install Python 3.8 through a Personal Package Archive (PPA) like the deadsnakes PPA. Execute the following command sequences:
$ sudo apt install software-properties-common $ sudo add-apt-repository ppa:deadsnakes/ppa $ sudo apt update $ sudo apt install python 3.8
If you are a fan of other Linux distros, then there is a high chance that Python3 is already pre-installed on your system by default if you make regular system updates and upgrades. Alternatively, if for some reason your OS system does not host Python 3, you can install it via the distribution package manager associated with your Linux OS. Fedora users, for instance, can use the dnf distribution package manager to install Python 3, as demonstrated below:
$ sudo dnf install python3.8
You should check your distribution package manager access to the most recent Python version installable on your Linux system as there may be multiple Python version support like the case with the Fedora distro.
Since installing Python 3 does not make Python 2.7 obsolete on your system, you have to be specific on how you use each of them. Removing Python 2.7 from your Linux OS might be a bad idea since other system services, features, and apps might still be depending on it. The following two commands distinguish between the usage of Python 2.7 and Python 3.x versions, respectively.
$ python $ python3
Setup Tools and PIP
These two, setuptools and pip third-party Python packages, are critical in Python’s functional delivery and performance. We utilize them through the terminal or command-line utility to manage compliant Python software packages via the download, install, and uninstall command arguments. Since we are currently prioritizing Python 3.x version usage, these tools or Python dependencies are installed by default during its installation. You can check the pip version you have through the following command.
$ pip3 -V
Virtual Environment Installation and Organization
A virtual environment helps organize and manage different dependencies and versions for your different projects like in Django. You can separate these dependencies and store them in different places to not collide. For instance, you might have project A that requires a dependency of version 2.x and Project B that requires a dependency of version 3.x. A virtual environment comfortably separates these two projects to not exist under one roof. A virtual environment is good for the management of your projects to know the exact dependencies applicable to a specific project. It also saves you from installing and using Python packages globally, breaking your other projects or the system tools currently in use. To install a virtual environment, we will borrow the PIP tool’s functionality.
$ python3 -m pip install --user virtualenv
Before you create and use virtual environments for your Django projects, you should designate a separate folder on your Linux OS with a name like my_projects_envs where you will be creating and managing different Virtual environments applicable to different project configurations.
Creating or initializing a virtual environment is as easy as following the following command syntax.
python3 -m venv preferred_name_of_your_virtual_environment
For example, you can create a virtual environment with the name myenv as follows.
$ python3 -m venv myenv
To use this virtual environment, you will need to activate it.
$ source myenv/bin/activate
If the command is successful, you will get a prefix like the following on your terminal.
To deactivate and stop using the virtual environment, run the following simple command on your terminal, and the virtual environment prefix will disappear.
(myenv) $ deactivate
With PIP and Virtual Environment installed and configurable on your Linux system, you can now install Python-supported packages like Django. Installing Django is straightforward, and since you might find yourselves working with different projects that implement different Django versions, it is important you learn how to install it flexibly.
(myenv) $ pip install django (myenv_two) $ pip install django==2.0 (myenv_three) $ pip install django>=2.0
The three created virtual environments above will work with three different Django versions as defined upon their installation.
Setting Up a Django Project
Now that you have Django installed, you have to take care of some initial setup before your project skeleton is complete. This initial setup complies with the auto-generation of some code to give life to your project. You can think of it as adding a battery to your Django project for it to breathe some life. Here, we define a Django project that unravels application-specific settings, Django-specific options, and Database configurations.
You will also need to create a primary directory that will cater to your different Django projects code. Let us create a Django project called mysite.
(myenv) $ django-admin startproject mysite
The naming convention of your Django project also matters, and you should avoid using names related to built-in Django or Python components like django and test. The directory structure of the created mysite Django project looks like the following.
The root directory /mysite is the container that holds your Django project. Django allows you to edit it to any other name. If you decide to do so, you will have to rename every instance of it pre-defined.
The manage.py python file works as a command-line utility and enables you to have an in-depth interaction with your Django project. You will find yourself using it a lot on the terminal.
Your project’s actual Python package is defined by the inner mysite/ directory under the main mysite/ directory. We use it for Python import purposes. For example, when you want to deal with the urls.py file under it, you implement an import connection like mysite.urls.
The mysite/__init__.py file is an empty identifier file. When Python looks inside a defined project directory and finds such a file name, it will right away acknowledge it as a Python package.
The mysite/settings.py file implements some important Django settings for your project’s smooth operation.
The mysite/urls.py file is used to map your project views under the views.py file to a web interface so that a target user or users can interact with what you created. More on this is under URL dispatcher.
The mysite/asgi.py and mysite/wsgi.py files work as entry-points for ASGI-compatible and WSGI-compatible project web servers. There is more to learn on ASGI and WSGI deployment through their related links if still interested.
Running the Django Server
You need to be inside the mysite/ root project directory to run your Django development server without any issues.
(myenv) $ python3 manage.py runserver
You can also use an alternate internal IP server port by changing it from the terminal.
(myenv) $ python3 manage.py runserver 8050
Creating a Django App
Now that we have defined a Django project and understood the directory structure and components linked to it, we can relate it to the book analogy mentioned earlier. The defined Django project is like the book’s hardcover, and the Django app(s) we will be working with are the book pages. Django project houses and manages the Django apps. These apps define our projects’ uniqueness and can be a poll app, a dating app, a database management app, or even a blogsite. There is no limit to the number of apps you can define and implement under a single Django project. You can explore as much as you want.
If we take the Django documentation approach of creating an app, we could start by defining a polls app.
(myenv) $ python3 manage.py startapp polls
The directory tree for this polls app will be similar to the following screenshot.
Under the polls/ directory structure, we have the views.py file responsible for what you see when you interact with a deployed Django project from a web app or interface. We can create a simple view with the following Python code segment.
# polls/views.py #django imports declarations from django.http import HttpResponse #created views def home (requests): return HttpResponse ("Welcome to the Home Page of your first Django app")
The Django view’s implementation is so simple that you don’t need to style and configure Django app templates to execute it. We need to have a URL to access it from a web browser interface.
If you create and add a urls.py file under the polls/ directory, its new structure will be similar to the following:
You can populate this urls.py file with the following code data.
#polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ]
Before we can access what we have just created from a web browser, the remaining step is to link our polls.urls module with the root or main mysite/urls.py file.
#mysite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('ActivePolls/', include('polls.urls')), path('admin/', admin.site.urls), ]
Run your Django development server if it’s not already running and visit the link http://127.0.0.1:8000/ActivePolls/ and you should be able to view the message we created in the polls/views.py file.
The other two important files to consider under the polls/ directory before concluding on our Django project skeleton tutorial are polls/admin.py and polls/models.py. Before we go there, we also need to clear the air on some configuration and file structure issues. It is advisable that after creating a Django app like the polls app we created, you should add it under mysite/settings.py file as depicted below.
It helps the defined Django project link with the man apps you are actively developing. Under the polls/ directory, you can also create the polls/forms.py file to deal with front-end instances that might require a project to register users, login users, subscribe users, and even query stored information on an app’s database.
When dealing with a Django database setup after creating a new app, a single database table needs to exist regarding the created app name, even if empty. To create an empty database for our polls app, we will run the following command.
(myenv) $ python3 manage.py migrate
This command creates the default needed database tables for the polls app. You can open the polls/models.py file and populate it with some definitive details.
#polls/models.py from django.db import models class Question (models.Model): poll_question = models.CharField(max_length=300) date_pub = models.DateTimeField('Published On')
Since we are dealing with a simple poll app, we created a database model to hold the poll questions. The python3 manage.py migrate command we executed earlier created the database instance of the polls app but did not implement it since we had not defined the db tables. Since we now have a db model we can work with, we should fully set up the polls database.
(myenv) $ python3 manage.py makemigrations polls
You should expect such an activity on your terminal after executing the above command.
Now that we have a db model instance, we need to activate the default Django admin site interface to interact with our created model. The following command should get the job done.
(myenv) $ python3 manage.py createsuperuser
You will be prompted to enter the needed username, email, and password to use under the Django admin site. Run your development server if it’s not already running and access the following Url to get to the Django admin interface:
You will be met with an interface similar to the one above.
After a successful login, the admin site will look similar to the one below.
The created Question model is not yet visible because we are yet to register it under polls/admin.py. We can achieve it through the following code structure.
#polls/admin.py from django.contrib import admin from .model import Question admin.site.register (Question)
Now if you reload the URL http://127.0.0.1:8000/admin/ you should see the Question model on display.
You can now be able to add a Question model through the Django admin interface and edit it if necessary.
This article has covered the basic information and understanding you need to jump on board a moving Django project or yet to be created. You can use this information to create a perfect Django project skeleton that can be implemented on all your app ideas to avoid referencing the hundreds of blogs on the internet to help you make your first Django steps comfortably. If you need more practical tips on conquering Django, follow this link.