Django, the web framework Python programmers use to build websites and applications, allows developers to build their own apps by extending the functionality that’s already there. These reusable bits of code are called apps and can be used over and over again in different projects, giving you time to focus on unique features. Aspiring web developers often ask what language they should learn first. The answer: it depends. Different languages are better suited for different purposes. But if your goal is to create dynamic and interactive webpages, then you should learn Django.
Django is a powerful web development framework that enables you to build complex websites with minimal code. In this article, we will discuss how to create your first app in Django. Let's get started,
Setting up Virtual Environment
Before doing all of these you need to ensure that the correct version of python is being installed on your system. You can install python from their official website.
After setting up python on your system, we need to do two things, the first is to set up a virtual environment for our projects and the second is to install Django. A virtual environment is an isolated Python environment that allows you to install packages without affecting other Python projects. To create a virtual environment, you will need to use a virtual environment manager such as "virtualenv" or pyvenv.
Here I'm going to use virtualenv. You can simply install using pip:
$ pip install virtualenvwrapper
Now that our virtualenv wrapper is installed. Let's see how we can make a virtual environment.
In order to create a virtual environment, you need to use this command "mkvirtualenv <VE name>"
$ mkvirtualenv devcreated virtual environment CPython3.10.0.final.0-64 in 21540ms
Activating the virtual environment:
workon dev(dev) $
Installing Django
After setting up the virtual environment, it's time to install Django. run:
$ pip install django
This will install the latest version of Django. To make sure everything is installed correctly, you can use the command "django-admin --version". If it shows the version of Django installed on your system, you're good to go.
Creating the first project
The first step in creating your Django app is to create a new project, type in the command:
$ django-admin startproject myproject
This will create a folder that contains some files like this:
Inside your project folder, you'll find a python file "manage.py". The manage.py file is a Python script that allows you to interact with your Django project. With the manage.py file, you can start the development server, create new Django apps, etc.
Creating the first App
An app in Django is basically a set of codes for performing a specific task. Instead of creating just one big website, Django lets you create many smaller sites, each working independently from the other. Think about it like having multiple websites on one domain name. A typical Django project is composed of three apps: a dashboard app (site), an admin app (site), and possibly more than one app for users and content creation.
For creating an App in Django you just need to enter the project directory, in my case it's (myproject), and type the following command:
$ cd myprojects$ python manage.py startapp myapp
This will create an app called 'myapp' in the project directory. If you look at the app folder, you'll see some files regarding the development of the app,
Registering App in settings
After creating an App, the first thing you should do is to register it in settings.py installed apps. Head over to the settings.py file in the projects directory and navigate to installed apps,
myproject/settings.py
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',# Nwely created app'myapp']
URL Routing
In order for your Django app to interact with web browsers, you’ll need URL routing. Django comes with an easy-to-use routing system that allows you to define URLs and associate them with specific views. The steps below will show you how to use Django’s URL router in your first Django app.
First, you need to go to urls.py in your Django project folder and add the path of your app where Django can find it,
myproject/urls.py
from django.contrib import adminfrom django.urls import path, include # Importing include functionurlpatterns = [path('admin/', admin.site.urls),path('',include("myapp.urls")) # Adding the path of app urls]
Now let's create another urls.py file in the App directory,
After creating the urls.py in the App Directory, you need to specify where the app needs to go when the URL is being called in the address bar.
myapp/urls.py
from django.urls import pathfrom.import viewsurlpatterns = [path('', views.index, name='index'),]
The code imports views from the current directory. It then creates a list of URL patterns called URL patterns. The first element in the list is an empty string. This means that when the user goes to the root URL of the web application, they will be directed to the index function in the views. But we haven't yet created a function that handles the request. So let's see how it can be done
Handling Requests
In order to handle the requests, we need to create a function in the views.py file that handles every data coming through. Let's define a function in our views,
def index(request):return render(request, 'home.html')
This function accepts a request coming from the client-side and sends an HTML file back as a response. Which is what the whole web does.
Now let's create our 'home.html' file inside a folder called templates in our home directory.
TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [os.path.join(BASE_DIR, 'templates')], # Templates directory'APP_DIRS': True,'OPTIONS': {'context_processors': ['django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},},]
home.html
<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Hello World</title></head><body><h1>Hello World!</h1></body></html>
Open the terminal and run the Django developement server using the command:
(dev) $ python manage.py runserver
And you'll see the page renderd in localhost:8000