This introductory Python Django Tutorial explains the steps to create your first project in Django:
Django is a Python Web framework, which is a collection of modules that make development easier. The modules are grouped to help us to create applications or websites from an existing source.
In this tutorial, we will be guiding you through the structure of a Django project. Before beginning, it’s good if you have the latest version of Python and Django installed on your system.
What You Will Learn:
- Python Django Tutorial
Python Django Tutorial
Django can be described as a high-level Python Web framework that helps in quick development and simple & practical design.
As Django has been provided by experienced developers, they have put efforts to take care of much of the complexities involved in Web development so the developer can focus on writing a perfectly functioning app without wasting time and efforts on something that already exists. It is free and open-source as well.
Django has been around for over a decade now. During this period, a lot of top websites have used it in production, some notable examples are Udemy, Washington Post, NASA, Spotify, National Geographic, The Guardian.
To sell an already free and open-source Django to you, we would highlight a couple of its advantages from many:
- Django and Python are Core Solutions in the Internet of Things, Blue chip companies, IT giants (NASA, Google, etc.), and FinTech companies in Silicon Valley. Do you know what this means? Learning the language and its popular framework should guarantee you employment or, at least give the possibility to create your product as an outsourcing company.
- It provides the best security. The framework has protection against XSS and CSRF attacks, SQL injections, clickjacking, and various other such intrusions. For one thing, Django hides your website’s source code.
How To Create A Django Project
We will be using Python 3.6.3, Django 2.2, PyCharm editor, and Anaconda prompt for coding and execution. Let’s jump onto the five steps for creating this project.
Step #1: Create A New Django Project
Different projects are created for different types of work. Usually, one entire website is considered to be a single project. For creating a new project, open the Anaconda Prompt on your computer (either search it in the Start Menu or open directly from installed files).
After the prompt opens, create the new project using the below command:
In the displayed command project location D: inside folder “project”, we are going to create a project named “New_Project” by running the mentioned command in Anaconda prompt. Avoid using names like Django (which will conflict with Django itself) or test (which conflicts with a built-in Python package).
The basic structure of the project is created.
A brief explanation about the files:
- The outer (first) New_Project/ root directory is just a container for your project.
- The inner New_Project / directory is the actual Python package for your project.
- manage.py: This file provides a command-line utility to interact with the Django project created by the developer in different ways. It mainly configures the Django settings automatically so that the configurations can be looked specifically into the project’s settings.py file.
- settings.py: Most of the important configurations of the project are done by default by Django during the time of installation and they are present inside this file.
- init.py: This is an empty file that tells the Django project that this directory should be considered as a Python package.
- urls.py: It contains URL declarations for this Django project, it can be considered as a “table of contents” of your Django-powered site. This is one of the most important files that manage the navigations of the website.
- wsgi.py: It is the entry-point of the project you created and serves the WSGI-compatible web servers. WSGI stands for Web Server Gateway Interface, it is a convention for web servers to forward the frameworks written in the Python programming language to the requested web applications.
Hurray!! We are done with the first step. To get some good vibes that you have created something just after completing Step 1, you can straight away run the server using the command: python manage.py runserver on the Anaconda prompt.
Paste the generated address to run your website, preferably on the Chrome browser. The address might be the local server address http://XXX.0.0.1:XXXX. The page which is now displayed on the browser is the default page provided by Django.
Note: When you run the command python manage.py runserver in the Anaconda prompt the Django server is started, on which the project implemented can be run. Every time if there is any update in the project, the server needs to be restarted to see the changes.
Once the server is running, the website can be run by accessing the address generated on running the above command. Use the Ctrl+Break key on the prompt, whenever the server needs to be stopped.
Step #2: Create Apps In The Project
What is the difference between a project and an app? An app is a Web application that does some specific task in the project – Example, a file upload section, a database of public records, or a simple poll app.
Whereas, the project is a collection of configuration and apps for a particular website. A project can contain multiple apps. A single app can be present in different projects.
Create a new app named “App_One” using the below:
Use any name relevant to the function of the app, avoid conflicting names such as “test”, “application” etc.
The app is created, in which “views.py” is the most important file. It will contain all the python code required for the functioning of each app. Also, the output of the python functions can be transferred to the Html to be displayed on the website, from the views file.
Your app directory should look as shown below:
To access the view (views.py file), we need to map it to a URL and for this, we need to create a file called urls.py manually inside the app.
To create the file, right-click on the folder “App_One” (created app), then select new python file and rename it exactly as “urls.py”. Similarly, create another app named “App_Two” and urls.py file inside it. For each app, it is necessary to create the respective urls.py file.
After creating the apps, it is important to include these apps in the Django’s “settings.py” file. It helps Django to identify the apps and apply necessary settings for them.
Follow the below points:
a) Open the “apps.py” file inside your app and copy the highlighted name (only, E.g. AppOneConfig) of the class displayed in it, as shown below.
b) Open projects “settings.py” file created in Step 1. Now you need to include the new apps in the list “INSTALLED_APPS”, in the format ‘<app name>.apps.<class name>’ (the class name is copied from the previous point) as shown in the below image.
New apps are added under INSTALLED_APPS in settings.py.
This completes Step #2 of the project, now just three more steps are remaining. Please do not forget to save each file individually after creating/updating.
Step #3: Creating Templates For The Front-end Development
By template, we mean Html pages. In your app “App_One” create a new folder named “Templates” and inside this “Templates” folder create another new folder with the name just as the same as the app name “App_One”.
Now a question may arise as to why is there a need to create another folder with the same name as that of the app. It is because in the case of a large project (website) there are multiple apps, and each app will contain a folder named Templates for the front-end pages.
Django searches for the folder “Templates” to implement your front end and as soon as it finds the first “Templates” folder, it stops searching for others, so in that case, it will never reach the next apps.
Therefore, a subfolder with the same name as that of the app name inside the Templates folder helps Django identify each app’s Templates uniquely.
Now, the app will look as shown below:
Similarly, this can be done for all the apps. You can see the Html file “home.html”, this will be the landing page for our website. In home.html, you can write the Html code for your landing page. We will be using a basic Html page to proceed.
Step #4: Mapping URLs For Each Html Page And Linking It With Python Code
This step is the soul of your Django project, hence understand it clearly.
a) Mapping URLs to Different Apps: Go to your first urls.py file, which is under the main folder “New_Project” that was created in Step 1 (not inside the apps you created in Step 2). That is the file, which Django searches for the URLs of the website as shown in the below image.
By default, Django has basic code already present in the urls.py file, you just need to add your URLs in “urlpatterns” list present there.
Here, we have added just lines 21 and 22 to include the URL files of the apps created earlier. Be careful about following the proper list format, ensure putting a comma (,) after each entry
Now let’s see what line 21, path(‘app1/’, include(‘App_One.urls’)) does.
As soon as you run the website and access the URL(website url) “127.0.0.1:8000/app1”, Django will search for identifier “app1/” in urls.py file and after reading line 21, it will take the URL flow to the App_One’s “urls.py” file that we created in Step 2.
Similarly, line 22 will take you to the “urls.py” file of App_Two on encountering URL “app2/”. Note that we have used URLs “app1” and “app2” just for explanation, you can use any identifier for the apps that you want.
Note: We just want to highlight that by following this practice of keeping URLs related to different apps in app-specific url.py file, would help in creating big websites easily and allow making changes without any confusion.
b) Mapping URLs from app to HTML pages: After the flow is transferred to App_One’s urls.py file, Django searches the next identifiers of the requested URL here.
Open the urls.py file inside the app “App_One”. You need to import the views (views.py file of the app) file here as all python code will be placed in this file.
Consider the URL requested by the user http://127.0.0.1:8000/app1/page2. After identifying the first identifier “app1”, Django will come to the file shown in the image. Now it will only search for the identifier “page2”, it will not look for “app1” again.
Hence, we can say that after matching the first identifier successfully, Django in a way crops it for finding the next.
So here, what line 7 path (‘page2’, views.page2) does, is that when the URL completely matches till the last identifier “page2”, it will send the request to the Python function “def page2(request)” written inside the views.py file of the same app. Managing flow in the view file is explained in the next step.
Similarly, if the requested URL is http://127.0.0.1:8000/app1/ the flow will go to line 6 and home function of the views.py file.
Step #5: Writing Views (views.py File Where Python Resides)
In the views.py file of each app, the python code is written specifically to that app only. It is a good practice to write different functions for each task, by navigating flow to different templates. In this way, the modularity is improved and proper structuring of the project is ensured. For example, you can refer below the image of the views.py file.
views.py file of App_One
In Step 4 when the views.home is requested on the URL matching, the home() function written in views.py file is called. Here, to keep things simple this function simply transfers the control onto the home.html file.
You can write Python code inside these functions and display the results on the Html pages, as we have done in the function page2(), line 11.
To display the Python functions output of the webpages of the website, the results need to be sent from the views.py file to the destined Html file.
Here each Python function returns a “render” method to the Html file. The Html file is specifically the file that is dependent on this python function for the output. Three parameters are passed, inside the render function.
The first one is the request object for the Html file, the second parameter is the template (Html file) name, along with its containing folder. The third parameter is the optional one, in which a python dictionary data structure is allowed.
You can see in the image that the template names (Html files) in returning lines are prefixed with the folder name in which they are present, to uniquely identify the templates folder(which we discussed in the previous points).
Finally!! Our first project is ready and the output would look as shown below. To run your first Django project simply open the anaconda prompt and run the server. After the server start, the project could be run on the browser using URL: 127.0.0.1:8000/home
On clicking the button “PAGE 2”, the page2.html is opened by using the urls.py file.
Similarly, you can code your way through to App2 and many other big websites that you are now ready to design.
We explored all about Django in this tutorial. The Structure of the Django Project was explained in a step-by-step manner along with the concerned pictorial representation for your easy understanding.
Suggested reading =>> Django Vs Flask: A Comparison