Django is one of the most popular Python Web frameworks. It is particularly powerful when dealing with data-driven applications, where the primary goal is to provide a front end to a database. Django comes with a number of built-in features to simplify the development process. This article describes how to install, use, and create your first Django project.
What is Django?
Django, pronounced “jango,” is a free open source framework that was first released in 2005. Django is named after the famous jazz guitarist Django Reinhardt. Many Python frameworks have been developed over the years, but Django is one of the most popular because of its flexibility and security.
Django is suitable for both front-end and back-end Web development. Integrated Python libraries make rapid development easy. Django has been widely accepted in all walks of life. Due to its growing popularity, it has become easier for providers to support Django applications on their platforms.
The application type
Django provides a complete framework solution, which means it provides everything you need for a rapid deployment project. Django offers excellent out-of-the-box security, a large user community, and can be extended on demand. For these reasons, it is considered the framework of choice by many developers. Using Django, you can develop complex database-driven Web applications, including:
- Machine learning
- E-commerce platform
- The data analysis
- Content management
Django and Flask
While both frameworks can meet the needs of your next Python application, each provides specific levels of functionality and support. Let’s take a quick look at the differences.
Django | Flask |
---|---|
The whole stack frame | Lightweight Web Framework |
Ideal for data-driven applications | Applies to existing apis and services |
Maybe more of a learning curve | The learning curve may be shorter |
Out-of-the-box security | Additional libraries required for security |
Custom HTML template engine | Jinja HTML template engine |
Both Django and Flask provide huge benefits for your projects. Depending on the time requirements of application development, one may be more suitable than the other. When choosing a framework, consider the type and complexity of the application and the end product.
Install Django
To create a hello_Django folder, either by command or manually, open CMD and navigate to the folder you just created.
Windows
// create virtual environment python -m venv venv // Activate virtual environment.\\venv\\Scripts\\ActivateCopy the code
Django installation
The most common way to manage Python packages is to use requirements or requirements.txt files. The requirements. TXT file is a list of packaged applications to use. Let’s create our requirements. TXT file, add Django, and install the library.
-
In Visual Studio Code, create a new file called requirements.txt in the hello_Django folder. * * * *
-
Add the following text to requirements.txt.
Text copied
Django Copy the code
-
From the terminal window, run the following command to install Django and any other packages listed in requirements.txt.
Hard copy
pip install -r requirements.txt Copy the code
With this command, the Django framework will start downloading. Once the download is complete, we can start developing our application.
Projects and Applications
project | The application |
---|---|
There is only one project. | You can have multiple applications in a single project. |
Contains the necessary Settings or applications for a particular site. | Is part of a larger site. |
The project is not used in other projects. | Applications can be used across multiple projects. |
view
Views are another component of a Django application that provides specific functionality within the application. A view contains all the necessary code to return a particular response when requested, such as a template or an image. Requests can even be redirected to another page if they do not follow the necessary logic within the function.
Site map
Call the URL mapping URLconf in Django and use it as the directory for your application. After requesting the URL, the module finds the appropriate link in the project and redirects the request to the view file contained in the application. The view then processes the request and performs the necessary actions.
As you continue to learn and have more complex file structures, you will add more views and urls to your application. This URLconf function is critical because it allows you to manage and organize urls in your application in a simple way. It also provides greater freedom to change the path root without breaking the application.
Start of actual combat
Create a project using Django-admin
As mentioned earlier, a Django project is a container for our entire project and any applications we create. Let’s create our project.
In the editor’s terminal window, run the following command:
django-admin startproject helloproject .
Copy the code
The trailing period at the end of a command is important. It indicatesdjango-admin
Use the current folder. If you do not use a period, it creates an additional subdirectory.
After running the above command, the new project should now be in the directory of your choice. In this case, you will see a new folder called HelloProject.
Explore the project structure
Now that you’ve created your Django project, let’s take a look at the structure and see what’s included.
manage.py
helloproject/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
Copy the code
-
The command-line utility manage.py is created in each Django project. It has the same functionality as Django-admin. The following example shows how to use it if you are in the project folder and want to see the subcommands available.
python manage.py help Copy the code
-
Helloproject is considered the Python package for your project.
-
Init. py is an empty file that tells Python that the directory should be treated as a package.
-
Settings.py contains all of your Settings or configurations.
-
Urls.py contains the urls in the project.
-
Asgi.py and wsgi.py serve as entry points for Web servers, depending on the type of server deployed.
Run the project
Now that Django is installed, a project has been created, and we’ve reviewed the project structure, it’s time to make sure that our project works.
-
In the terminal window, enter the following code to start the server.
python manage.py runserver Copy the code
This project performs system checks and starts your development server. Copy and paste the URL for your development server (should be http://localhost:8000) into your preferred browser. You should see a Django** congratulations ** page with an image of a rocket taking off.
- Temporarily stop the server because we need to reconfigure our project. In the terminal window, select Ctrl+C.
Create the Hello World application
We’ve looked at the basics of the Django framework and examined the folder structure of our project. Now it’s time to create our first application! Hello this world! App will help you understand how applications are created and how they work with Django projects.
From the terminal window, run the following command to create the application.
python manage.py startapp hello_world
Copy the code
Using this command, Django creates the required folders and files, and you should now see the following structure.
hello_world/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
Copy the code
Understand paths and views
Views and paths (or routes) are at the heart of any Web framework. They are used to determine what information should be displayed to the user and how the user will access it. Django also uses these concepts.
The path
All applications allow users to perform different methods or functions through some mechanism. This action may be clicking a button in a mobile application or executing a command from the command line.
In a Web application, user requests are made in the following manner:
- Navigate to different urls.
- Type it in.
- Select the link.
- Click a button.
Routes tell Django whether a user requests a particular URL or path, and what function to perform.
URL likehttps://adventure-works.com/about might perform a function called about. URLhttps://adventure-works.com/login might execute a function called authentication.
The paths in Django are created by configuring urlPatterns. These patterns determine what Django should look for in the URL a user requests, and determine which function should handle the request. These patterns are collected into the module URLconf that Django calls.
view
The view determines what information should be returned to the user. A view is a function or class that executes code in response to a user request. They return HTML or some other type of response, such as a 404 error.
Create a view
-
In the IDE, open views.py, which will be in hello_world.
-
Replace the code in views.py with the following:
from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world!" )Copy the code
The helper function HttpResponse allows you to return text or other primitive types to the caller
Create a path
Once the view is created, the next step is to map it to the appropriate URL or path.
-
In the IDE, create a file called urls.py in hello_world.
-
Add the following code to your new urls.py.
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] Copy the code
The most important part of this code is the UrlPatterns tuple. This tuple is where views and urls are connected or mapped. As you can see, we’ve already imported the views.py file, so we can use it in the urlPatterns line.
Our registeredURLconf
The project of
We created the new URLconf in our hello_world application. Since this project controls all user requests, we need URLconf to register ours in the core urls.py file, which is located in helloProject.
-
Open urls.py in helloProject. * * * *
-
Note the documentation comments at the beginning. These comments explain how to register a new URLconf module.
-
Replace the line read with from Django. urls import path the following import statement adds include and path.
from django.urls import include, path Copy the code
Usinginclude allows us to import the URLconf module, and path is used to identify the URLconf.
-
In the list, add the following code below the line read in urlPatterns = [:
path('', include('hello_world.urls')), Copy the code
This code registers our URLconf.
The code below the documentation comment should now look like the following example:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('hello_world.urls')),
path('admin/', admin.site.urls),
]
Copy the code
Run your first application
The structure is complete, the view is added, and the URL is mapped. Now it’s time to run your application!
-
In the Terminal window of Visual Studio Code, run the following command to start the server again.
python manage.py runserver Copy the code
-
Open the URL in your preferred browser:
http:// local host :8000/
You should see hello now, world!